summaryrefslogtreecommitdiff
path: root/sql/field.cc
blob: 5a618a5a2a962d2271e3f6c70bd5695bc1f6a915 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
/*
   Copyright (c) 2000, 2017, Oracle and/or its affiliates.
   Copyright (c) 2008, 2022, MariaDB

   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-1335  USA
*/

/**
  @file

  @brief
  This file implements classes defined in field.h
*/

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

#include "mariadb.h"
#include "sql_priv.h"
#include "sql_select.h"
#include "rpl_rli.h"                            // Pull in Relay_log_info
#include "slave.h"                              // Pull in rpl_master_has_bug()
#include "strfunc.h"                            // find_type2, find_set
#include "tztime.h"                      // struct Time_zone
#include "filesort.h"                    // change_double_for_sort
#include "log_event.h"                   // class Table_map_log_event
#include <m_ctype.h>

// Maximum allowed exponent value for converting string to decimal
#define MAX_EXPONENT 1024

/*****************************************************************************
  Instantiate templates and static variables
*****************************************************************************/

static const char *zero_timestamp="0000-00-00 00:00:00.000000";
LEX_CSTRING temp_lex_str= {STRING_WITH_LEN("temp")};

uchar Field_null::null[1]={1};
const char field_separator=',';

#define DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE FLOATING_POINT_BUFFER
#define LONGLONG_TO_STRING_CONVERSION_BUFFER_SIZE 128
#define DECIMAL_TO_STRING_CONVERSION_BUFFER_SIZE 128
#define BLOB_PACK_LENGTH_TO_MAX_LENGH(arg) \
                        ((ulong) ((1LL << MY_MIN(arg, 4) * 8) - 1))

// Column marked for read or the field set to read out of record[0]
bool Field::marked_for_read() const
{
  return !table ||
         (!table->read_set ||
          bitmap_is_set(table->read_set, field_index) ||
          (!(ptr >= table->record[0] &&
             ptr < table->record[0] + table->s->reclength)));
}

/*
  The name of this function is a bit misleading as in 10.4 we don't
  have to test anymore if the field is computed. Instead we mark
  changed fields with DBUG_FIX_WRITE_SET() in table.cc
*/

bool Field::marked_for_write_or_computed() const
{
  return (!table ||
          (!table->write_set ||
           bitmap_is_set(table->write_set, field_index) ||
           (!(ptr >= table->record[0] &&
              ptr < table->record[0] + table->s->reclength))));
}


#define FLAGSTR(S,F) ((S) & (F) ? #F " " : "")

/*
  Rules for merging different types of fields in UNION

  NOTE: to avoid 256*256 table, gap in table types numeration is skipped
  following #defines describe that gap and how to canculate number of fields
  and index of field in this array.
*/
const int FIELDTYPE_TEAR_FROM= (MYSQL_TYPE_BIT + 1);
const int FIELDTYPE_TEAR_TO=   (MYSQL_TYPE_NEWDECIMAL - 1);
const int FIELDTYPE_LAST=      254;
const int FIELDTYPE_NUM=       FIELDTYPE_TEAR_FROM + (FIELDTYPE_LAST -
                                                      FIELDTYPE_TEAR_TO);

static inline int merge_type2index(enum_field_types merge_type)
{
  DBUG_ASSERT(merge_type < FIELDTYPE_TEAR_FROM ||
              merge_type > FIELDTYPE_TEAR_TO);
  DBUG_ASSERT(merge_type <= FIELDTYPE_LAST);
  if (merge_type < FIELDTYPE_TEAR_FROM)
    return merge_type;
  return FIELDTYPE_TEAR_FROM + (merge_type - FIELDTYPE_TEAR_TO) - 1;
}


/**
  Implements data type merge rules for the built-in traditional data types.
  Used for operations such as:
  - UNION
  - CASE and its abbreviations COALESCE, IF, IFNULL
  - LEAST/GREATEST

  Given Fields A and B of real_types a and b, we find the result type of
  COALESCE(A, B) by querying:
    field_types_merge_rules[field_type_to_index(a)][field_type_to_index(b)].
*/
static enum_field_types field_types_merge_rules [FIELDTYPE_NUM][FIELDTYPE_NUM]=
{
  /* MYSQL_TYPE_DECIMAL -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_NEWDECIMAL,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_NEWDECIMAL,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_NEWDECIMAL,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_TINY -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_TINY,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_SHORT,       MYSQL_TYPE_LONG,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_TINY,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_INT24,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_SHORT -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_SHORT,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_SHORT,       MYSQL_TYPE_LONG,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_SHORT,       MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_INT24,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_SHORT,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_LONG -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_LONG,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_LONG,        MYSQL_TYPE_LONG,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_LONG,         MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_LONG,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_LONG,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_FLOAT -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_FLOAT,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_FLOAT,       MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_FLOAT,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_FLOAT,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_DOUBLE -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_NULL -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_TINY,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_SHORT,       MYSQL_TYPE_LONG,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_NULL,        MYSQL_TYPE_TIMESTAMP,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_LONGLONG,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_TIME,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_YEAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_BIT,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_ENUM,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_SET,         MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_TIMESTAMP -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_TIMESTAMP,   MYSQL_TYPE_TIMESTAMP,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_DATETIME,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_LONGLONG -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_LONGLONG,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_LONGLONG,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_LONGLONG,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_LONGLONG,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_INT24 -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_INT24,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_INT24,       MYSQL_TYPE_LONG,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_INT24,       MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_INT24,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_INT24,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL    MYSQL_TYPE_ENUM
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_DATE -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_DATETIME,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_DATETIME,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,  MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_TIME -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_TIME,        MYSQL_TYPE_DATETIME,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_TIME,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_DATETIME -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_DATETIME,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_DATETIME,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_YEAR -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_TINY,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_SHORT,       MYSQL_TYPE_LONG,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_YEAR,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_INT24,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_YEAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_NEWDATE -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_DATETIME,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_DATETIME,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_VARCHAR -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_VARCHAR
  },
  /* MYSQL_TYPE_BIT -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_BIT,         MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_BIT,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_NEWDECIMAL -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_NEWDECIMAL,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_NEWDECIMAL,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_NEWDECIMAL,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_NEWDECIMAL,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_ENUM -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_ENUM,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_SET -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_SET,         MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_TINY_BLOB -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_TINY_BLOB
  },
  /* MYSQL_TYPE_MEDIUM_BLOB -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_MEDIUM_BLOB
  },
  /* MYSQL_TYPE_LONG_BLOB -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_LONG_BLOB
  },
  /* MYSQL_TYPE_BLOB -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_BLOB
  },
  /* MYSQL_TYPE_VAR_STRING -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_VARCHAR
  },
  /* MYSQL_TYPE_STRING -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_STRING,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_STRING,      MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING
    MYSQL_TYPE_STRING
  }
};


const Type_handler *
Type_handler::aggregate_for_result_traditional(const Type_handler *a,
                                               const Type_handler *b)
{
  if (a == b)
  {
    /*
      If two traditional handlers are equal, quickly return "a".
      Some handlers (e.g. Type_handler_bool) pretend to be traditional,
      but in fact they are not traditional in full extent, they are
      only sub-types for now (and don't have a corresponding Field_xxx yet).
      Here we preserve such handlers during aggregation.
      As a result, COALESCE(true,true) preserves the "boolean" data type.

      Need to do this conversion for deprecated data types,
      similar to what field_type_merge_rules[][] does.
    */
    switch (a->field_type()) {
    case MYSQL_TYPE_DECIMAL:     return &type_handler_newdecimal;
    case MYSQL_TYPE_DATE:        return &type_handler_newdate;
    case MYSQL_TYPE_VAR_STRING:  return &type_handler_varchar;
    default: break;
    }
    return a;
  }
  enum_field_types ta= a->traditional_merge_field_type();
  enum_field_types tb= b->traditional_merge_field_type();
  enum_field_types res= field_types_merge_rules[merge_type2index(ta)]
                                               [merge_type2index(tb)];
  return Type_handler::get_handler_by_real_type(res);
}


bool Field::check_assignability_from(const Type_handler *from,
                                     bool ignore) const
{
  /*
    Using type_handler_for_item_field() here to get the data type handler
    on both sides. This is needed to make sure aggregation for Field
    works the same way with how Item_field aggregates for UNION or CASE,
    so these statements:
      SELECT a FROM t1 UNION SELECT b FROM t1; // Item_field vs Item_field
      UPDATE t1 SET a=b;                       // Field      vs Item_field
    either both return "Illegal parameter data types" or both pass
    the data type compatibility test.
    For MariaDB standard data types, using type_handler_for_item_field()
    turns ENUM/SET into just CHAR.
  */
  Type_handler_hybrid_field_type th(type_handler()->
                                      type_handler_for_item_field());
  if (th.aggregate_for_result(from->type_handler_for_item_field()))
  {
    bool error= (!ignore && get_thd()->is_strict_mode()) ||
                (type_handler()->is_scalar_type() != from->is_scalar_type());
    /*
      Display fully qualified column name for table columns.
      Display non-qualified names for other things,
      e.g. SP variables, SP return values, SP and CURSOR parameters.
    */
    if (table->s->db.str && table->s->table_name.str)
      my_printf_error(ER_ILLEGAL_PARAMETER_DATA_TYPES2_FOR_OPERATION,
                      "Cannot cast '%s' as '%s' in assignment of %`s.%`s.%`s",
                      MYF(error ? 0 : ME_WARNING),
                      from->name().ptr(), type_handler()->name().ptr(),
                      table->s->db.str, table->s->table_name.str,
                      field_name.str);
    else
      my_printf_error(ER_ILLEGAL_PARAMETER_DATA_TYPES2_FOR_OPERATION,
                      "Cannot cast '%s' as '%s' in assignment of %`s",
                      MYF(error ? 0 : ME_WARNING),
                      from->name().ptr(), type_handler()->name().ptr(),
                      field_name.str);
    return error;
  }
  return false;
}


/*
  Test if the given string contains important data:
  not spaces for character string,
  or any data for binary string.

  SYNOPSIS
    test_if_important_data()
    cs          Character set
    str         String to test
    strend      String end

  RETURN
    FALSE - If string does not have important data
    TRUE  - If string has some important data
*/

static bool
test_if_important_data(CHARSET_INFO *cs, const char *str, const char *strend)
{
  if (cs != &my_charset_bin)
    str+= cs->scan(str, strend, MY_SEQ_SPACES);
  return (str < strend);
}


/**
   Function to compare two unsigned integers for their relative order.
   Used below. In an anonymous namespace to not clash with definitions
   in other files.
 */

CPP_UNNAMED_NS_START

int compare(unsigned int a, unsigned int b)
{
  if (a < b)
    return -1;
  if (b < a)
    return 1;
  return 0;
}

CPP_UNNAMED_NS_END


/*****************************************************************************
  Static help functions
*****************************************************************************/

/*
  @brief
    Create a fixed size sort key part

  @param  buff           buffer where values are written
  @param  length         fixed size of the sort column
*/

void Field::make_sort_key_part(uchar *buff,uint length)
{
  if (maybe_null())
  {
    if (is_null())
    {
      bzero(buff, length + 1);
      return;
    }
    *buff++= 1;
  }
  sort_string(buff, length);
}


/*
  @brief
    Create a packed sort key part

  @param  buff           buffer where values are written
  @param  sort_field     sort column structure

  @retval
    length of the bytes written, does not include the NULL bytes
*/
uint
Field::make_packed_sort_key_part(uchar *buff,
                                 const SORT_FIELD_ATTR *sort_field)
{
  if (maybe_null())
  {
    if (is_null())
    {
      *buff++= 0;
      return 0;  // For NULL values don't write any data
    }
    *buff++=1;
  }
  sort_string(buff, sort_field->original_length);
  return sort_field->original_length;
}


uint
Field_longstr::make_packed_sort_key_part(uchar *buff,
                                         const SORT_FIELD_ATTR *sort_field)
{
  if (maybe_null())
  {
    if (is_null())
    {
      *buff++= 0;
      return 0;   // For NULL values don't write any data
    }
    *buff++=1;
  }
  uchar *end= pack_sort_string(buff, sort_field);
  return (uint) (end-buff);
}


uchar*
Field_longstr::pack_sort_string(uchar *to, const SORT_FIELD_ATTR *sort_field)
{
  StringBuffer<LONGLONG_BUFFER_SIZE+1> buf;
  val_str(&buf, &buf);
  return to + sort_field->pack_sort_string(to, &buf, field_charset());
}


/**
  @brief
  Determine the relative position of the field value in a numeric interval

  @details
  The function returns a double number between 0.0 and 1.0 as the relative
  position of the value of the this field in the numeric interval of [min,max].
  If the value is not in the interval the the function returns 0.0 when
  the value is less than min, and, 1.0 when the value is greater than max.

  @param  min  value of the left end of the interval
  @param  max  value of the right end of the interval

  @return
  relative position of the field value in the numeric interval [min,max] 
*/

double pos_in_interval_for_double(double midp_val, double min_val,
                                  double max_val)
{
  double n, d;
  n= midp_val - min_val;
  if (n < 0)
    return 0.0;
  d= max_val - min_val;
  if (d <= 0)
    return 1.0;
  return MY_MIN(n/d, 1.0);
}


double Field::pos_in_interval_val_real(Field *min, Field *max)
{
  return pos_in_interval_for_double(val_real(), min->val_real(),
                                    max->val_real());
}


static
inline ulonglong char_prefix_to_ulonglong(uchar *src)
{
  uint sz= sizeof(ulonglong);
  for (uint i= 0; i < sz/2; i++)
  {
    uchar tmp= src[i];
    src[i]= src[sz-1-i];
    src[sz-1-i]= tmp;
  }
  return uint8korr(src); 
}

/*
  Compute res = a - b, without losing precision and taking care that these are
  unsigned numbers.
*/
static inline double safe_substract(ulonglong a, ulonglong b)
{
  return (a > b)? double(a - b) : -double(b - a);
}


/**
  @brief
  Determine the relative position of the field value in a string interval

  @details
  The function returns a double number between 0.0 and 1.0 as the relative
  position of the value of the this field in the string interval of [min,max].
  If the value is not in the interval the the function returns 0.0 when
  the value is less than min, and, 1.0 when the value is greater than max.

  @note
  To calculate the relative position of the string value v in the interval
  [min, max] the function first converts the beginning of these three
  strings v, min, max into the strings that are used for byte comparison.
  For each string not more sizeof(ulonglong) first bytes are taken
  from the result of conversion. Then these bytes are interpreted as the
  big-endian representation of an ulonglong integer. The values of these
  integer numbers obtained for the strings v, min, max are used to calculate
  the position of v in [min,max] in the same way is it's done for numeric
  fields (see Field::pos_in_interval_val_real).

  @todo
  Improve the procedure for the case when min and max have the same
  beginning
     
  @param  min  value of the left end of the interval
  @param  max  value of the right end of the interval

  @return
  relative position of the field value in the string interval [min,max] 
*/

double Field::pos_in_interval_val_str(Field *min, Field *max, uint data_offset)
{
  return pos_in_interval_for_string(charset(),
            ptr      + data_offset, data_length(),
            min->ptr + data_offset, min->data_length(),
            max->ptr + data_offset, max->data_length()
         );
}


double pos_in_interval_for_string(CHARSET_INFO *cset,
                                  const uchar *midp_val, uint32 midp_len,
                                  const uchar *min_val,  uint32 min_len,
                                  const uchar *max_val,  uint32 max_len)
{
  uchar mp_prefix[sizeof(ulonglong)];
  uchar minp_prefix[sizeof(ulonglong)];
  uchar maxp_prefix[sizeof(ulonglong)];
  ulonglong mp, minp, maxp;

  cset->strnxfrm(mp_prefix, sizeof(mp), midp_val, midp_len);
  cset->strnxfrm(minp_prefix, sizeof(minp), min_val, min_len);
  cset->strnxfrm(maxp_prefix, sizeof(maxp), max_val, max_len);

  mp=   char_prefix_to_ulonglong(mp_prefix);
  minp= char_prefix_to_ulonglong(minp_prefix);
  maxp= char_prefix_to_ulonglong(maxp_prefix);

  double n, d;
  n= safe_substract(mp, minp);
  if (n < 0)
    return 0.0;
  d= safe_substract(maxp, minp);
  if (d <= 0)
    return 1.0;
  return MY_MIN(n/d, 1.0);
}


bool Field::test_if_equality_guarantees_uniqueness(const Item *item) const
{
  DBUG_ASSERT(cmp_type() != STRING_RESULT); // For STRING_RESULT see Field_str
  /*
    We use result_type() rather than cmp_type() in the below condition,
    because it covers a special case that string literals guarantee uniqueness
    for temporal columns, so the query:
      WHERE temporal_column='string'
    cannot return multiple distinct temporal values.

    TODO: perhaps we could allow INT/DECIMAL/DOUBLE types for temporal items.
  */
  return result_type() == item->result_type();
}


/**
  Check whether a field item can be substituted for an equal item

  @details
  The function checks whether a substitution of a field item for
  an equal item is valid.

  @param arg   *arg != NULL <-> the field is in the context
               where substitution for an equal item is valid

  @note
    The following statement is not always true:
  @n
    x=y => F(x)=F(x/y).
  @n
    This means substitution of an item for an equal item not always
    yields an equavalent condition. Here's an example:
    @code
    'a'='a '
    (LENGTH('a')=1) != (LENGTH('a ')=2)
  @endcode
    Such a substitution is surely valid if either the substituted
    field is not of a STRING type or if it is an argument of
    a comparison predicate.

  @retval
    TRUE   substitution is valid
  @retval
    FALSE  otherwise
*/

bool Field::can_be_substituted_to_equal_item(const Context &ctx,
                                             const Item_equal *item_equal)
{
  DBUG_ASSERT(item_equal->compare_type_handler()->cmp_type() != STRING_RESULT);
  DBUG_ASSERT(cmp_type() != STRING_RESULT);
  switch (ctx.subst_constraint()) {
  case ANY_SUBST:
    /*
      Disable const propagation for items used in different comparison contexts.
      This must be done because, for example, Item_hex_string->val_int() is not
      the same as (Item_hex_string->val_str() in BINARY column)->val_int().
      We cannot simply disable the replacement in a particular context (
      e.g. <bin_col> = <int_col> AND <bin_col> = <hex_string>) since
      Items don't know the context they are in and there are functions like
      IF (<hex_string>, 'yes', 'no').
    */
    return ctx.compare_type_handler() == item_equal->compare_type_handler();
  case IDENTITY_SUBST:
    return true;
  }
  return false;
}


bool Field::cmp_is_done_using_type_handler_of_this(const Item_bool_func *cond,
                                                   const Item *item) const
{
  /*
    We could eventually take comparison_type_handler() from cond,
    instead of calculating it again. But only some descendants of
    Item_bool_func has this method. So this needs some hierarchy changes.
    Another option is to pass "class Context" to this method.
  */
  Type_handler_hybrid_field_type cmp(type_handler_for_comparison());
  return !cmp.aggregate_for_comparison(item->type_handler_for_comparison()) &&
         cmp.type_handler() == type_handler_for_comparison();
}


/*
  This handles all numeric and BIT data types.
*/ 
bool Field::can_optimize_keypart_ref(const Item_bool_func *cond,
                                     const Item *item) const
{
  DBUG_ASSERT(cmp_type() != STRING_RESULT);
  DBUG_ASSERT(cmp_type() != TIME_RESULT);
  return item->cmp_type() != TIME_RESULT;
}


/*
  This handles all numeric and BIT data types.
*/ 
bool Field::can_optimize_group_min_max(const Item_bool_func *cond,
                                       const Item *const_item) const
{
  DBUG_ASSERT(cmp_type() != STRING_RESULT);
  DBUG_ASSERT(cmp_type() != TIME_RESULT);
  return const_item->cmp_type() != TIME_RESULT;
}


/*
  This covers all numeric types, BIT
*/
bool Field::can_optimize_range(const Item_bool_func *cond,
                               const Item *item,
                               bool is_eq_func) const
{
  DBUG_ASSERT(cmp_type() != TIME_RESULT);   // Handled in Field_temporal
  DBUG_ASSERT(cmp_type() != STRING_RESULT); // Handled in Field_str descendants
  return item->cmp_type() != TIME_RESULT;
}


int Field::store_hex_hybrid(const char *str, size_t length)
{
  DBUG_ASSERT(result_type() != STRING_RESULT);
  ulonglong nr;

  if (length > 8)
  {
    nr= flags & UNSIGNED_FLAG ? ULONGLONG_MAX : LONGLONG_MAX;
    goto warn;
  }
  nr= (ulonglong) longlong_from_hex_hybrid(str, length);
  if ((length == 8) && !(flags & UNSIGNED_FLAG) && (nr > LONGLONG_MAX))
  {
    nr= LONGLONG_MAX;
    goto warn;
  }
  return store((longlong) nr, true);  // Assume hex numbers are unsigned

warn:
  if (!store((longlong) nr, true))
    set_warning(Sql_condition::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
  return 1;
}


/**
  If a field does not have a corresponding data, it's behavior can vary:
  - In case of the fixed file format
    it's set to the default value for the data type,
    such as 0 for numbers or '' for strings.
  - In case of a non-fixed format
    it's set to NULL for nullable fields, and
    it's set to the default value for the data type for NOT NULL fields.
  This seems to be by design.
*/
bool Field::load_data_set_no_data(THD *thd, bool fixed_format)
{
  reset();                  // Do not use the DEFAULT value
  if (fixed_format)
  {
    set_notnull();
    /*
      We're loading a fixed format file, e.g.:
        LOAD DATA INFILE 't1.txt' INTO TABLE t1 FIELDS TERMINATED BY '';
      Suppose the file ended unexpectedly and no data was provided for an
      auto-increment column in the current row.
      Historically, if sql_mode=NO_AUTO_VALUE_ON_ZERO, then the column value
      is set to 0 in such case (the next auto_increment value is not used).
      This behaviour was introduced by the fix for "bug#12053" in mysql-4.1.
      Note, loading a delimited file works differently:
      "no data" is not converted to 0 on NO_AUTO_VALUE_ON_ZERO:
      it's considered as equal to setting the column to NULL,
      which is then replaced to the next auto_increment value.
      This difference seems to be intentional.
    */
    if (this == table->next_number_field)
      table->auto_increment_field_not_null= true;
  }
  set_has_explicit_value(); // Do not auto-update this field
  return false;
}


bool Field::load_data_set_null(THD *thd)
{
  reset();
  set_null();
  if (!maybe_null())
  {
    if (this != table->next_number_field)
      set_warning(Sql_condition::WARN_LEVEL_WARN, ER_WARN_NULL_TO_NOTNULL, 1);
  }
  set_has_explicit_value(); // Do not auto-update this field
  return false;
}


void Field::load_data_set_value(const char *pos, uint length,
                                CHARSET_INFO *cs)
{
  /*
    Mark field as not null, we should do this for each row because of
    restore_record...
  */
  set_notnull();
  if (this == table->next_number_field)
    table->auto_increment_field_not_null= true;
  store(pos, length, cs);
  set_has_explicit_value(); // Do not auto-update this field
}


bool Field::sp_prepare_and_store_item(THD *thd, Item **value)
{
  DBUG_ENTER("Field::sp_prepare_and_store_item");
  DBUG_ASSERT(value);

  Item *expr_item;

  if (!(expr_item= thd->sp_fix_func_item_for_assignment(this, value)))
    goto error;

  /* Save the value in the field. Convert the value if needed. */

  expr_item->save_in_field(this, 0);

  if (likely(!thd->is_error()))
    DBUG_RETURN(false);

error:
  /*
    In case of error during evaluation, leave the result field set to NULL.
    Sic: we can't do it in the beginning of the function because the 
    result field might be needed for its own re-evaluation, e.g. case of 
    set x = x + 1;
  */
  set_null();
  DBUG_ASSERT(thd->is_error());
  DBUG_RETURN(true);
}


void Field::error_generated_column_function_is_not_allowed(THD *thd,
                                                           bool error) const
{
  StringBuffer<64> tmp;
  vcol_info->expr->print(&tmp, (enum_query_type)
                               (QT_TO_SYSTEM_CHARSET |
                                QT_ITEM_IDENT_SKIP_DB_NAMES |
                                QT_ITEM_IDENT_SKIP_TABLE_NAMES));
  my_error(ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED,
           MYF(error ? 0 : ME_WARNING),
           tmp.c_ptr_safe(), vcol_info->get_vcol_type_name(),
           const_cast<const char*>(field_name.str));
}


/*
  Check if an indexed or a persistent virtual column depends on sql_mode flags
  that it cannot handle.
  See sql_mode.h for details.
*/
bool Field::check_vcol_sql_mode_dependency(THD *thd, vcol_init_mode mode) const
{
  DBUG_ASSERT(vcol_info);
  if ((flags & PART_KEY_FLAG) != 0 || stored_in_db())
  {
    Sql_mode_dependency valdep= vcol_info->expr->value_depends_on_sql_mode();
    sql_mode_t cnvdep= conversion_depends_on_sql_mode(thd, vcol_info->expr);
    Sql_mode_dependency dep=
        (valdep | Sql_mode_dependency(0, cnvdep)) &
        Sql_mode_dependency(~0, ~can_handle_sql_mode_dependency_on_store());
    if (dep)
    {
      bool error= (mode & VCOL_INIT_DEPENDENCY_FAILURE_IS_ERROR) != 0;
      error_generated_column_function_is_not_allowed(thd, error);
      dep.push_dependency_warnings(thd);
      return error;
    }
  }
  return false;
}


bool Field::make_empty_rec_store_default_value(THD *thd, Item *item)
{
  DBUG_ASSERT(!(flags & BLOB_FLAG));
  int res= item->save_in_field(this, true);
  return res != 0 && res != 3;
}


/**
  Numeric fields base class constructor.
*/
Field_num::Field_num(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg,
                     uchar null_bit_arg, utype unireg_check_arg,
                     const LEX_CSTRING *field_name_arg,
                     decimal_digits_t dec_arg, bool zero_arg, bool unsigned_arg)
  :Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
         unireg_check_arg, field_name_arg),
  dec(dec_arg),zerofill(zero_arg),unsigned_flag(unsigned_arg)
{
  if (zerofill)
    flags|=ZEROFILL_FLAG;
  if (unsigned_flag)
    flags|=UNSIGNED_FLAG;
}


void Field_num::prepend_zeros(String *value) const
{
  int diff;
  if ((diff= (int) (field_length - value->length())) > 0)
  {
    const bool error= value->realloc(field_length);
    if (likely(!error))
    {
      bmove_upp((uchar*) value->ptr()+field_length,
                (uchar*) value->ptr()+value->length(),
	        value->length());
      bfill((uchar*) value->ptr(),diff,'0');
      value->length(field_length);
    }
  }
}


sql_mode_t Field_num::can_handle_sql_mode_dependency_on_store() const
{
  return MODE_PAD_CHAR_TO_FULL_LENGTH;
}


Item *Field_num::get_equal_zerofill_const_item(THD *thd, const Context &ctx,
                                               Item *const_item)
{
  switch (ctx.subst_constraint()) {
  case IDENTITY_SUBST:
    return NULL; // Not safe to propagate if not in comparison. See MDEV-8369.
  case ANY_SUBST:
    break;
  }
  DBUG_ASSERT(const_item->const_item());
  DBUG_ASSERT(ctx.compare_type_handler()->cmp_type() != STRING_RESULT);
  return const_item;
}


/**
Construct warning parameters using thd->no_errors
  to determine whether to generate or suppress warnings.
  We can get here in a query like this:
    SELECT COUNT(@@basedir);
  from Item_func_get_system_var::update_null_value().
*/
Value_source::Warn_filter::Warn_filter(const THD *thd)
 :m_want_warning_edom(!thd->no_errors),
  m_want_note_truncated_spaces(!thd->no_errors)
{ }


/**
  Check string-to-number conversion and produce a warning if
  - could not convert any digits (EDOM-alike error)
  - found garbage at the end of the string
  - found trailing spaces (a note)
  See also Field_num::check_edom_and_truncation() for a similar function.

  @param thd        - the thread
  @param filter     - which warnings/notes are allowed
  @param type       - name of the data type (e.g. "INTEGER", "DECIMAL", "DOUBLE")
  @param cs         - character set of the original string
  @param str        - the original string
  @param end        - the end of the string

  Unlike Field_num::check_edom_and_truncation(), this function does not
  distinguish between EDOM and truncation and reports the same warning for
  both cases. Perhaps we should eventually print different warnings, to make
  the explicit CAST work closer to the implicit cast in Field_xxx::store().
*/
void
Value_source::Converter_string_to_number::check_edom_and_truncation(THD *thd,
                                                       Warn_filter filter,
                                                       const char *type,
                                                       CHARSET_INFO *cs,
                                                       const char *str,
                                                       size_t length) const
{
  DBUG_ASSERT(str <= m_end_of_num);
  DBUG_ASSERT(m_end_of_num <= str + length);
  if (m_edom || (m_end_of_num < str + length &&
                 !check_if_only_end_space(cs, m_end_of_num, str + length)))
  {
    // EDOM or important trailing data truncation
    if (filter.want_warning_edom())
    {
      /*
        We can use err.ptr() here as ErrConvString is guaranteed to put an
        end \0 here.
      */
      THD *wthd= thd ? thd : current_thd;
      push_warning_printf(wthd, Sql_condition::WARN_LEVEL_WARN,
                          ER_TRUNCATED_WRONG_VALUE,
                          ER_THD(wthd, ER_TRUNCATED_WRONG_VALUE), type,
                          ErrConvString(str, length, cs).ptr());
    }
  }
  else if (m_end_of_num < str + length)
  {
    // Unimportant trailing data (spaces) truncation
    if (filter.want_note_truncated_spaces())
    {
      THD *wthd= thd ? thd : current_thd;
      push_warning_printf(wthd, Sql_condition::WARN_LEVEL_NOTE,
                          ER_TRUNCATED_WRONG_VALUE,
                          ER_THD(wthd, ER_TRUNCATED_WRONG_VALUE), type,
                          ErrConvString(str, length, cs).ptr());
    }
  }
}


/**
  Check a string-to-number conversion routine result and generate warnings
  in case when it:
  - could not convert any digits
  - found garbage at the end of the string.

  @param type          Data type name (e.g. "decimal", "integer", "double")
  @param edom          Indicates that the string-to-number routine returned
                       an error code equivalent to EDOM (value out of domain),
                       i.e. the string fully consisted of garbage and the
                       conversion routine could not get any digits from it.
  @param str           The original string
  @param length        Length of 'str'
  @param cs            Character set
  @param end           Pointer to char after last used digit

  @note
    This is called after one has called one of the following functions:
    - strntoull10rnd()
    - strntod()
    - str2my_decimal()

  @retval
    0        OK
  @retval
    1        error: could not scan any digits (EDOM),
             e.g. empty string, or garbage.
  @retval
    2        error: scanned some digits,
             but then found garbage at the end of the string.
*/


int Field_num::check_edom_and_important_data_truncation(const char *type,
                                                        bool edom,
                                                        CHARSET_INFO *cs,
                                                        const char *str, size_t length,
                                                        const char *end)
{
  /* Test if we get an empty string or garbage */
  if (edom)
  {
    ErrConvString err(str, length, cs);
    set_warning_truncated_wrong_value(type, err.ptr());
    return 1;
  }
  /* Test if we have garbage at the end of the given string. */
  if (test_if_important_data(cs, end, str + length))
  {
    set_warning(WARN_DATA_TRUNCATED, 1);
    return 2;
  }
  return 0;
}


int Field_num::check_edom_and_truncation(const char *type, bool edom,
                                         CHARSET_INFO *cs,
                                         const char *str, size_t length,
                                         const char *end)
{
  int rc= check_edom_and_important_data_truncation(type, edom,
                                                   cs, str, length, end);
  if (!rc && end < str + length)
    set_note(WARN_DATA_TRUNCATED, 1);
  return rc;
}


/*
  Convert a string to an integer then check bounds.
  
  SYNOPSIS
    Field_num::get_int
    cs            Character set
    from          String to convert
    len           Length of the string
    rnd           OUT longlong value
    unsigned_max  max unsigned value
    signed_min    min signed value
    signed_max    max signed value

  DESCRIPTION
    The function calls strntoull10rnd() to get an integer value then
    check bounds and errors returned. In case of any error a warning
    is raised.

  RETURN
    0   ok
    1   error
*/

bool Field_num::get_int(CHARSET_INFO *cs, const char *from, size_t len,
                        longlong *rnd, ulonglong unsigned_max, 
                        longlong signed_min, longlong signed_max)
{
  char *end;
  int error;
  
  *rnd= (longlong) cs->strntoull10rnd(from, len,
                                      unsigned_flag, &end,
                                      &error);
  if (unsigned_flag)
  {

    if ((((ulonglong) *rnd > unsigned_max) &&
         (*rnd= (longlong) unsigned_max)) ||
        error == MY_ERRNO_ERANGE)
    {
      goto out_of_range;
    }
  }
  else
  {
    if (*rnd < signed_min)
    {
      *rnd= signed_min;
      goto out_of_range;
    }
    else if (*rnd > signed_max)
    {
      *rnd= signed_max;
      goto out_of_range;
    }
  }
  if (get_thd()->count_cuted_fields > CHECK_FIELD_EXPRESSION &&
      check_int(cs, from, len, end, error))
    return 1;

  return error && get_thd()->count_cuted_fields == CHECK_FIELD_EXPRESSION;

out_of_range:
  set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
  return 1;
}


double Field_real::get_double(const char *str, size_t length, CHARSET_INFO *cs,
                              int *error)
{
  char *end;
  double nr= cs->strntod((char*) str, length, &end, error);
  if (unlikely(*error))
  {
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
    *error= 1;
  }
  else if (get_thd()->count_cuted_fields > CHECK_FIELD_EXPRESSION &&
           check_edom_and_truncation("double", str == end,
                                     cs, str, length, end))
    *error= 1;
  return nr;
}


/**
  Process decimal library return codes and issue warnings for overflow and
  truncation.

  @param op_result  decimal library return code (E_DEC_* see include/decimal.h)

  @retval
    1  there was overflow
  @retval
    0  no error or some other errors except overflow
*/

int Field::warn_if_overflow(int op_result)
{
  if (op_result == E_DEC_OVERFLOW)
  {
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
    return 1;
  }
  if (op_result == E_DEC_TRUNCATED)
  {
    set_note(WARN_DATA_TRUNCATED, 1);
    /* We return 0 here as this is not a critical issue */
  }
  return 0;
}


/**
  Interpret field value as an integer but return the result as a string.

  This is used for printing bit_fields as numbers while debugging.
*/

String *Field::val_int_as_str(String *val_buffer, bool unsigned_val)
{
  DBUG_ASSERT(marked_for_read());
  CHARSET_INFO *cs= &my_charset_bin;
  uint length;
  longlong value= val_int();

  if (val_buffer->alloc(MY_INT64_NUM_DECIMAL_DIGITS))
    return 0;
  length= (uint) (cs->longlong10_to_str)((char*) val_buffer->ptr(),
                                         MY_INT64_NUM_DECIMAL_DIGITS,
                                         unsigned_val ? 10 : -10,
                                         value);
  val_buffer->length(length);
  return val_buffer;
}


/// This is used as a table name when the table structure is not set up
Field::Field(uchar *ptr_arg,uint32 length_arg,uchar *null_ptr_arg,
	     uchar null_bit_arg,
	     utype unireg_check_arg, const LEX_CSTRING *field_name_arg)
  :ptr(ptr_arg),
  null_ptr(null_ptr_arg), table(0), orig_table(0),
  table_name(0), field_name(*field_name_arg), option_list(0),
  option_struct(0), key_start(0), part_of_key(0),
  part_of_key_not_clustered(0), part_of_sortkey(0),
  unireg_check(unireg_check_arg), invisible(VISIBLE), field_length(length_arg),
  null_bit(null_bit_arg), is_created_from_null_item(FALSE),
  read_stats(NULL), collected_stats(0), vcol_info(0), check_constraint(0),
  default_value(0)
{
  flags=null_ptr ? 0: NOT_NULL_FLAG;
  comment.str= (char*) "";
  comment.length=0;
  field_index= 0;
  cond_selectivity= 1.0;
  next_equal_field= NULL;
}


void Field::hash_not_null(Hasher *hasher)
{
  DBUG_ASSERT(marked_for_read());
  DBUG_ASSERT(!is_null());
  hasher->add(sort_charset(), ptr, pack_length());
}

size_t
Field::do_last_null_byte() const
{
  DBUG_ASSERT(null_ptr == NULL || null_ptr >= table->record[0]);
  if (null_ptr)
    return (size_t) (null_ptr - table->record[0]) + 1;
  return LAST_NULL_BYTE_UNDEF;
}


void Field::copy_from_tmp(int row_offset)
{
  memcpy(ptr,ptr+row_offset,pack_length());
  if (null_ptr)
  {
    *null_ptr= (uchar) ((null_ptr[0] & (uchar) ~(uint) null_bit) |
			(null_ptr[row_offset] & (uchar) null_bit));
  }
}


bool Field::send(Protocol *protocol)
{
  StringBuffer<MAX_FIELD_WIDTH> tmp(charset());
  val_str(&tmp);
  return protocol->store(tmp.ptr(), tmp.length(), tmp.charset());
}


bool Field_num::send_numeric_zerofill_str(Protocol_text *protocol,
                                          protocol_send_type_t send_type)
{
  DBUG_ASSERT(marked_for_read());
  StringBuffer<MAX_FIELD_WIDTH> tmp(&my_charset_latin1);
  val_str(&tmp);
  return protocol->store_numeric_zerofill_str(tmp.ptr(),
                                              tmp.length(),
                                              send_type);
}


/**
   Check to see if field size is compatible with destination.

   This method is used in row-based replication to verify that the
   slave's field size is less than or equal to the master's field
   size. The encoded field metadata (from the master or source) is
   decoded and compared to the size of this field (the slave or
   destination).

   @note

   The comparison is made so that if the source data (from the master)
   is less than the target data (on the slave), -1 is returned in @c
   <code>*order_var</code>. This implies that a conversion is
   necessary, but that it is lossy and can result in truncation of the
   value.

   If the source data is strictly greater than the target data, 1 is
   returned in <code>*order_var</code>. This implies that the source
   type can is contained in the target type and that a conversion is
   necessary but is non-lossy.

   If no conversion is required to fit the source type in the target
   type, 0 is returned in <code>*order_var</code>.

   @param   field_metadata   Encoded size in field metadata
   @param   mflags           Flags from the table map event for the table.
   @param   order_var        Pointer to variable where the order
                             between the source field and this field
                             will be returned.

   @return @c true if this field's size is compatible with the
   master's field size, @c false otherwise.
*/
bool Field::compatible_field_size(uint field_metadata,
                                  const Relay_log_info *rli_arg __attribute__((unused)),
                                  uint16 mflags __attribute__((unused)),
                                  int *order_var) const
{
  uint const source_size= pack_length_from_metadata(field_metadata);
  uint const destination_size= row_pack_length();
  DBUG_PRINT("debug", ("real_type: %d, source_size: %u, destination_size: %u",
                       real_type(), source_size, destination_size));
  *order_var = compare(source_size, destination_size);
  return true;
}


int Field::store(const char *to, size_t length, CHARSET_INFO *cs,
                 enum_check_fields check_level)
{
  Check_level_instant_set tmp_level(get_thd(), check_level);
  return store(to, length, cs);
}


int Field::store_text(const char *to, size_t length, CHARSET_INFO *cs,
                      enum_check_fields check_level)
{
  Check_level_instant_set tmp_level(get_thd(), check_level);
  return store_text(to, length, cs);
}


int Field::store_timestamp_dec(const timeval &ts, uint dec)
{
  return store_time_dec(Datetime(get_thd(), ts).get_mysql_time(), dec);
}


int Field::store_to_statistical_minmax_field(Field *field, String *val)
{
  val_str(val);
  size_t length= Well_formed_prefix(val->charset(), val->ptr(),
                 MY_MIN(val->length(), field->field_length)).length();
  return field->store(val->ptr(), length, &my_charset_bin);
}


int Field::store_from_statistical_minmax_field(Field *stat_field, String *str)
{
  stat_field->val_str(str);
  return store_text(str->ptr(), str->length(), &my_charset_bin);
}


/**
   Pack the field into a format suitable for storage and transfer.

   To implement packing functionality, only the virtual function
   should be overridden. The other functions are just convenience
   functions and hence should not be overridden.

   @note The default method for packing fields just copy the raw bytes
   of the record into the destination, but never more than
   <code>max_length</code> characters.

   @param to
   Pointer to memory area where representation of field should be put.

   @param from
   Pointer to memory area where record representation of field is
   stored.

   @param max_length
   Maximum length of the field, as given in the column definition. For
   example, for <code>CHAR(1000)</code>, the <code>max_length</code>
   is 1000. This information is sometimes needed to decide how to pack
   the data.

*/
uchar *
Field::pack(uchar *to, const uchar *from, uint max_length)
{
  uint32 length= pack_length();
  set_if_smaller(length, max_length);
  memcpy(to, from, length);
  return to+length;
}

/**
   Unpack a field from row data.

   This method is used to unpack a field from a master whose size of
   the field is less than that of the slave.

   The <code>param_data</code> parameter is a two-byte integer (stored
   in the least significant 16 bits of the unsigned integer) usually
   consisting of two parts: the real type in the most significant byte
   and a original pack length in the least significant byte.

   The exact layout of the <code>param_data</code> field is given by
   the <code>Table_map_log_event::save_field_metadata()</code>.

   This is the default method for unpacking a field. It just copies
   the memory block in byte order (of original pack length bytes or
   length of field, whichever is smaller).

   @param   to         Destination of the data
   @param   from       Source of the data
   @param   param_data Real type and original pack length of the field
                       data

   @return  New pointer into memory based on from + length of the data
   @return  0 if wrong data
*/
const uchar *
Field::unpack(uchar* to, const uchar *from, const uchar *from_end,
              uint param_data)
{
  uint length=pack_length(), len;
  int from_type= 0;
  /*
    If from length is > 255, it has encoded data in the upper bits. Need
    to mask it out.
  */
  if (param_data > 255)
  {
    from_type= (param_data & 0xff00) >> 8U;  // real_type.
    param_data= param_data & 0x00ff;        // length.
  }

  if ((param_data == 0) ||
      (length == param_data) ||
      (from_type != real_type()))
  {
    if (from + length > from_end)
      return 0;                                 // Error in data

    memcpy(to, from, length);
    return from+length;
  }

  len= (param_data && (param_data < length)) ? param_data : length;

  if (from + len > from_end)
    return 0;                                   // Error in data

  memcpy(to, from, len);
  return from+len;
}


void Field_num::add_zerofill_and_unsigned(String &res) const
{
  if (unsigned_flag)
    res.append(STRING_WITH_LEN(" unsigned"));
  if (zerofill)
    res.append(STRING_WITH_LEN(" zerofill"));
}


void Field::make_send_field(Send_field *field)
{
  if (orig_table && orig_table->s->db.str && *orig_table->s->db.str)
  {
    field->db_name= orig_table->s->db;
    if (orig_table->pos_in_table_list &&
        orig_table->pos_in_table_list->schema_table)
      field->org_table_name= Lex_cstring_strlen(orig_table->pos_in_table_list->
                                                schema_table->table_name);
    else
      field->org_table_name= orig_table->s->table_name;
  }
  else
    field->org_table_name= field->db_name= empty_clex_str;
  if (orig_table && orig_table->alias.ptr())
  {
    orig_table->alias.get_value(&field->table_name);
    field->org_col_name= field_name;
  }
  else
  {
    field->table_name= empty_clex_str;
    field->org_col_name= empty_clex_str;
  }
  field->col_name= field_name;
  field->length=field_length;
  field->set_handler(type_handler());
  field->flags=table->maybe_null ? (flags & ~NOT_NULL_FLAG) : flags;
  field->decimals= 0;
}


/**
  Conversion from decimal to longlong with checking overflow and
  setting correct value (min/max) in case of overflow.

  @param val             value which have to be converted
  @param unsigned_flag   type of integer in which we convert val
  @param err             variable to pass error code

  @return
    value converted from val
*/
longlong Field::convert_decimal2longlong(const my_decimal *val,
                                         bool unsigned_flag, int *err)
{
  longlong i;
  if (unsigned_flag)
  {
    if (val->sign())
    {
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      i= 0;
      *err= 1;
    }
    else if (warn_if_overflow(my_decimal2int((E_DEC_ERROR &
                                              ~E_DEC_OVERFLOW &
                                              ~E_DEC_TRUNCATED),
                                             val, TRUE, &i)))
    {
      i= ~(longlong) 0;
      *err= 1;
    }
  }
  else if (warn_if_overflow(my_decimal2int((E_DEC_ERROR &
                                            ~E_DEC_OVERFLOW &
                                            ~E_DEC_TRUNCATED),
                                           val, FALSE, &i)))
  {
    i= (val->sign() ? LONGLONG_MIN : LONGLONG_MAX);
    *err= 1;
  }
  return i;
}


/**
  Storing decimal in integer fields.

  @param val       value for storing

  @note
    This method is used by all integer fields, real/decimal redefine it

  @retval
    0     OK
  @retval
    !=0  error
*/

int Field_int::store_decimal(const my_decimal *val)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int err= 0;
  longlong i= convert_decimal2longlong(val, unsigned_flag, &err);
  return MY_TEST(err | store(i, unsigned_flag));
}


/**
  Return decimal value of integer field.

  @param decimal_value     buffer for storing decimal value

  @note
    This method is used by all integer fields, real/decimal redefine it.
    All longlong values fit in our decimal buffer which cal store 8*9=72
    digits of integer number

  @return
    pointer to decimal buffer with value of field
*/

my_decimal* Field_int::val_decimal(my_decimal *decimal_value)
{
  DBUG_ASSERT(marked_for_read());
  longlong nr= val_int();
  int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
  return decimal_value;
}


bool Field_int::get_date(MYSQL_TIME *ltime,date_mode_t fuzzydate)
{
  DBUG_ASSERT(marked_for_read());
  Longlong_hybrid nr(val_int(), (flags & UNSIGNED_FLAG));
  return int_to_datetime_with_warn(get_thd(), nr, ltime,
                                   fuzzydate, table->s, field_name.str);
}


bool Field_vers_trx_id::get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate, ulonglong trx_id)
{
  DBUG_ASSERT(marked_for_read());
  DBUG_ASSERT(ltime);
  if (!table || !table->s)
    return true;
  DBUG_ASSERT(table->versioned(VERS_TRX_ID) ||
    (table->versioned() && table->s->table_category == TABLE_CATEGORY_TEMPORARY));
  if (!trx_id)
    return true;

  THD *thd= get_thd();
  DBUG_ASSERT(thd);
  if (trx_id == ULONGLONG_MAX)
  {
    thd->variables.time_zone->gmt_sec_to_TIME(ltime, TIMESTAMP_MAX_VALUE);
    ltime->second_part= TIME_MAX_SECOND_PART;
    return false;
  }
  if (cached == trx_id)
  {
    *ltime= cache;
    return false;
  }

  TR_table trt(thd);
  bool found= trt.query(trx_id);
  if (found)
  {
    trt[TR_table::FLD_COMMIT_TS]->get_date(&cache, fuzzydate);
    *ltime= cache;
    cached= trx_id;
    return false;
  }

  push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
                      ER_VERS_NO_TRX_ID, ER_THD(thd, ER_VERS_NO_TRX_ID),
                      (longlong) trx_id);
  return true;
}


Field_str::Field_str(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg,
                     uchar null_bit_arg, utype unireg_check_arg,
                     const LEX_CSTRING *field_name_arg,
                     const DTCollation &collation)
  :Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
         unireg_check_arg, field_name_arg)
{
  m_collation= collation;
  if (collation.collation->state & MY_CS_BINSORT)
    flags|=BINARY_FLAG;
}


bool Field_str::test_if_equality_guarantees_uniqueness(const Item *item) const
{
  /*
    Can't guarantee uniqueness when comparing a CHAR/VARCHAR/TEXT,
    BINARY/VARBINARY/BLOB, ENUM,SET columns to an item with cmp_type()
    of INT_RESULT, DOUBLE_RESULT, DECIMAL_RESULT or TIME_RESULT.
    Example:
      SELECT * FROM t1 WHERE varchar_column=DATE'2001-01-01'
    return non-unuque values, e.g. '2001-01-01' and '2001-01-01x'.
  */
  if (!field_charset()->propagate(0, 0) ||
      item->cmp_type() != STRING_RESULT)
    return false;
  /*
    Can't guarantee uniqueness when comparing to
    an item of a different collation.
    Example:
      SELECT * FROM t1
      WHERE latin1_bin_column = _latin1'A' COLLATE latin1_swedish_ci
    return non-unique values 'a' and 'A'.
  */
  DTCollation tmp(dtcollation());
  return !tmp.aggregate(item->collation) && tmp.collation == field_charset();
}


bool Field_str::can_be_substituted_to_equal_item(const Context &ctx,
                                                  const Item_equal *item_equal)
{
  DBUG_ASSERT(item_equal->compare_type_handler()->cmp_type() == STRING_RESULT);
  switch (ctx.subst_constraint()) {
  case ANY_SUBST:
    return ctx.compare_type_handler() == item_equal->compare_type_handler() &&
          (ctx.compare_type_handler()->cmp_type() != STRING_RESULT ||
           ctx.compare_collation() == item_equal->compare_collation());
  case IDENTITY_SUBST:
    return ((charset()->state & MY_CS_BINSORT) &&
            (charset()->state & MY_CS_NOPAD));
  }
  return false;
}


void Field_str::change_charset(const DTCollation &new_cs)
{
  if (!has_charset())
    return;

  field_length= (field_length * new_cs.collation->mbmaxlen) /
    m_collation.collation->mbmaxlen;
  m_collation= new_cs;
}


void Field_num::make_send_field(Send_field *field)
{
  Field::make_send_field(field);
  field->decimals= dec;
}

/**
  Decimal representation of Field_str.

  @param d         value for storing

  @note
    Field_str is the base class for fields like Field_enum,
    Field_date and some similar. Some dates use fraction and also
    string value should be converted to floating point value according
    our rules, so we use double to store value of decimal in string.

  @todo
    use decimal2string?

  @retval
    0     OK
  @retval
    !=0  error
*/

int Field_str::store_decimal(const my_decimal *d)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  double val;
  /* TODO: use decimal2string? */
  int err= warn_if_overflow(my_decimal2double(E_DEC_FATAL_ERROR &
                                            ~E_DEC_OVERFLOW, d, &val));
  return err | store(val);
}


my_decimal *Field_str::val_decimal(my_decimal *decimal_value)
{
  DBUG_ASSERT(marked_for_read());
  longlong nr= val_int();
  int2my_decimal(E_DEC_FATAL_ERROR, nr, 0, decimal_value);
  return decimal_value;
}


uint Field::fill_cache_field(CACHE_FIELD *copy)
{
  uint store_length;
  copy->str= ptr;
  copy->length= pack_length_in_rec();
  copy->field= this;
  if (flags & BLOB_FLAG)
  {
    copy->type= CACHE_BLOB;
    copy->length-= portable_sizeof_char_ptr;
    return copy->length;
  }
  else if (!zero_pack() &&
           (type() == MYSQL_TYPE_STRING && copy->length >= 4 &&
            copy->length < 256))
  {
    copy->type= CACHE_STRIPPED;			    /* Remove end space */
    store_length= 2;
  }
  else if (type() ==  MYSQL_TYPE_VARCHAR)
  {
    copy->type= pack_length()-row_pack_length() == 1 ? CACHE_VARSTR1:
                                                      CACHE_VARSTR2;
    store_length= 0;
  }
  else
  {
    copy->type= 0;
    store_length= 0;
  }
  return copy->length + store_length;
}


bool Field::get_date(MYSQL_TIME *to, date_mode_t mode)
{
  StringBuffer<40> tmp;
  Temporal::Warn_push warn(get_thd(), nullptr, nullptr, nullptr, to, mode);
  Temporal_hybrid *t= new(to) Temporal_hybrid(get_thd(), &warn,
                                              val_str(&tmp), mode);
  return !t->is_valid_temporal();
}


longlong Field::val_datetime_packed(THD *thd)
{
  MYSQL_TIME ltime, tmp;
  if (get_date(&ltime, Datetime::Options_cmp(thd)))
    return 0;
  if (ltime.time_type != MYSQL_TIMESTAMP_TIME)
    return pack_time(&ltime);
  if (time_to_datetime_with_warn(thd, &ltime, &tmp, TIME_CONV_NONE))
    return 0;
  return pack_time(&tmp);
}


longlong Field::val_time_packed(THD *thd)
{
  MYSQL_TIME ltime;
  Time::Options_cmp opt(thd);
  if (get_date(&ltime, opt))
    return 0;
  if (ltime.time_type == MYSQL_TIMESTAMP_TIME)
    return pack_time(&ltime);
  // Conversion from DATETIME or DATE to TIME is needed
  return Time(thd, &ltime, opt).to_packed();
}


/**
  This is called when storing a date in a string.

  @note
    Needs to be changed if/when we want to support different time formats.
*/

int Field::store_time_dec(const MYSQL_TIME *ltime, uint dec)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  char buff[MAX_DATE_STRING_REP_LENGTH];
  uint length= (uint) my_TIME_to_str(ltime, buff, dec);
  /* Avoid conversion when field character set is ASCII compatible */
  return store(buff, length, (charset()->state & MY_CS_NONASCII) ?
                              &my_charset_latin1 : charset());
}


bool Field::optimize_range(uint idx, uint part) const
{
  return MY_TEST(table->file->index_flags(idx, part, 1) & HA_READ_RANGE);
}


Field *Field::make_new_field(MEM_ROOT *root, TABLE *new_table,
                             bool keep_type __attribute__((unused)))
{
  Field *tmp;
  if (!(tmp= (Field*) memdup_root(root,(char*) this,size_of())))
    return 0;

  if (tmp->table->maybe_null)
    tmp->flags&= ~NOT_NULL_FLAG;
  tmp->table= new_table;
  tmp->key_start.init(0);
  tmp->part_of_key.init(0);
  tmp->part_of_sortkey.init(0);
  /*
    TODO: it is not clear why this method needs to reset unireg_check.
    Try not to reset it, or explain why it needs to be reset.
  */
  tmp->unireg_check= Field::NONE;
  tmp->flags&= (NOT_NULL_FLAG | BLOB_FLAG | UNSIGNED_FLAG |
                ZEROFILL_FLAG | BINARY_FLAG | ENUM_FLAG | SET_FLAG);
  tmp->reset_fields();
  tmp->invisible= VISIBLE;
  return tmp;
}


Field *Field::new_key_field(MEM_ROOT *root, TABLE *new_table,
                            uchar *new_ptr, uint32 length,
                            uchar *new_null_ptr, uint new_null_bit)
{
  Field *tmp;
  if ((tmp= make_new_field(root, new_table, table == new_table)))
  {
    tmp->ptr=      new_ptr;
    tmp->null_ptr= new_null_ptr;
    tmp->null_bit= new_null_bit;
  }
  return tmp;
}


/**
  Create field for temporary table from given field.

  @param thd	        Thread handler
  @param table	        Temporary table
  @param maybe_null_arg If the result field should be NULL-able,
                        even if the original field is NOT NULL, e.g. for:
                        - OUTER JOIN fields
                        - WITH ROLLUP fields
                        - arguments of aggregate functions, e.g. SUM(column1)
  @retval               NULL, on error
  @retval               pointer to the new field created, on success.
*/

Field *Field::create_tmp_field(MEM_ROOT *mem_root, TABLE *new_table,
                               bool maybe_null_arg)
{
  Field *new_field;

  if ((new_field= make_new_field(mem_root, new_table, new_table == table)))
  {
    new_field->init_for_tmp_table(this, new_table);
    new_field->flags|= flags & NO_DEFAULT_VALUE_FLAG;
    if (maybe_null_arg)
      new_field->flags&= ~NOT_NULL_FLAG; // Because of outer join
  }
  return new_field;
}


/* This is used to generate a field in TABLE from TABLE_SHARE */

Field *Field::clone(MEM_ROOT *root, TABLE *new_table)
{
  Field *tmp;
  if ((tmp= (Field*) memdup_root(root,(char*) this,size_of())))
  {
    tmp->init(new_table);
    tmp->move_field_offset((my_ptrdiff_t) (new_table->record[0] -
                                           new_table->s->default_values));
  }
  return tmp;
}


Field *Field::clone(MEM_ROOT *root, TABLE *new_table, my_ptrdiff_t diff)
{
  Field *tmp;
  if ((tmp= (Field*) memdup_root(root,(char*) this,size_of())))
  {
    if (new_table)
      tmp->init(new_table);
    tmp->move_field_offset(diff);
  }
  return tmp;
}


int Field::set_default()
{
  if (default_value)
  {
    Query_arena backup_arena;
    /*
      TODO: this may impose memory leak until table flush.
          See comment in
          TABLE::update_virtual_fields(handler *, enum_vcol_update_mode).
    */
    table->in_use->set_n_backup_active_arena(table->expr_arena, &backup_arena);
    int rc= default_value->expr->save_in_field(this, 0);
    table->in_use->restore_active_arena(table->expr_arena, &backup_arena);
    return rc;
  }
  /* Copy constant value stored in s->default_values */
  my_ptrdiff_t l_offset= (my_ptrdiff_t) (table->s->default_values -
                                        table->record[0]);
  memcpy(ptr, ptr + l_offset, pack_length_in_rec());
  if (maybe_null_in_table())
    *null_ptr= ((*null_ptr & (uchar) ~null_bit) |
                (null_ptr[l_offset] & null_bit));
  return 0;
}


/****************************************************************************
  Field_null, a field that always return NULL
****************************************************************************/

void Field_null::sql_type(String &res) const
{
  res.set_ascii(STRING_WITH_LEN("null"));
}


bool Field_null::is_equal(const Column_definition &new_field) const
{
  DBUG_ASSERT(!compression_method());
  return new_field.type_handler() == type_handler() &&
         new_field.charset == field_charset() &&
         new_field.length == max_display_length();
}


/****************************************************************************
  Field_row, e.g. for ROW-type SP variables
****************************************************************************/

Field_row::~Field_row()
{
  delete m_table;
}


bool Field_row::sp_prepare_and_store_item(THD *thd, Item **value)
{
  DBUG_ENTER("Field_row::sp_prepare_and_store_item");

  if (value[0]->type() == Item::NULL_ITEM)
  {
    /*
      We're in a auto-generated sp_inst_set, to assign
      the explicit default NULL value to a ROW variable.
    */
    m_table->set_all_fields_to_null();
    DBUG_RETURN(false);
  }

  /**
    - In case if we're assigning a ROW variable from another ROW variable,
      value[0] points to Item_splocal. sp_fix_func_item() will return the
      fixed underlying Item_field pointing to Field_row.
    - In case if we're assigning from a ROW() value, src and value[0] will
      point to the same Item_row.
  */
  Item *src;
  if (!(src= thd->sp_fix_func_item(value)) ||
      src->cmp_type() != ROW_RESULT ||
      src->cols() != m_table->s->fields)
  {
    my_error(ER_OPERAND_COLUMNS, MYF(0), m_table->s->fields);
    m_table->set_all_fields_to_null();
    DBUG_RETURN(true);
  }

  DBUG_RETURN(m_table->sp_set_all_fields_from_item(thd, src));
}


/****************************************************************************
  Functions for the Field_decimal class
  This is an number stored as a pre-space (or pre-zero) string
****************************************************************************/

int
Field_decimal::reset(void)
{
  Field_decimal::store(STRING_WITH_LEN("0"),&my_charset_bin);
  return 0;
}

void Field_decimal::overflow(bool negative)
{
  uint len=field_length;
  uchar *to=ptr, filler= '9';

  set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
  if (negative)
  {
    if (!unsigned_flag)
    {
      /* Put - sign as a first digit so we'll have -999..999 or 999..999 */
      *to++ = '-';
      len--;
    }
    else
    {
      filler= '0';				// Fill up with 0
      if (!zerofill)
      {
	/*
	  Handle unsigned integer without zerofill, in which case
	  the number should be of format '   0' or '   0.000'
	*/
	uint whole_part=field_length- (dec ? dec+2 : 1);
	// Fill with spaces up to the first digit
	bfill(to, whole_part, ' ');
	to+=  whole_part;
	len-= whole_part;
	// The main code will also handle the 0 before the decimal point
      }
    }
  }
  bfill(to, len, filler);
  if (dec)
    ptr[field_length-dec-1]='.';
  return;
}


int Field_decimal::store(const char *from_arg, size_t len, CHARSET_INFO *cs)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  char buff[STRING_BUFFER_USUAL_SIZE];
  String tmp(buff,sizeof(buff), &my_charset_bin);
  const uchar *from= (uchar*) from_arg;

  /* Convert character set if the old one is multi uchar */
  if (cs->mbmaxlen > 1)
  { 
    uint dummy_errors;
    tmp.copy((char*) from, len, cs, &my_charset_bin, &dummy_errors);
    from= (uchar*) tmp.ptr();
    len=  tmp.length();
  }

  const uchar *end= from+len;
  /* The pointer where the field value starts (i.e., "where to write") */
  uchar *to= ptr;
  uint tmp_dec, tmp_uint;
  /*
    The sign of the number : will be 0 (means positive but sign not
    specified), '+' or '-'
  */
  uchar sign_char=0;
  /* The pointers where prezeros start and stop */
  const uchar *pre_zeros_from, *pre_zeros_end;
  /* The pointers where digits at the left of '.' start and stop */
  const uchar *int_digits_from, *int_digits_end;
  /* The pointers where digits at the right of '.' start and stop */
  const uchar *frac_digits_from, *frac_digits_end;
  /* The sign of the exponent : will be 0 (means no exponent), '+' or '-' */
  char expo_sign_char=0;
  uint exponent=0;                                // value of the exponent
  /*
    Pointers used when digits move from the left of the '.' to the
    right of the '.' (explained below)
  */
  const uchar *UNINIT_VAR(int_digits_tail_from);
  /* Number of 0 that need to be added at the left of the '.' (1E3: 3 zeros) */
  uint UNINIT_VAR(int_digits_added_zeros);
  /*
    Pointer used when digits move from the right of the '.' to the left
    of the '.'
  */
  const uchar *UNINIT_VAR(frac_digits_head_end);
  /* Number of 0 that need to be added at the right of the '.' (for 1E-3) */
  uint UNINIT_VAR(frac_digits_added_zeros);
  uchar *pos,*tmp_left_pos,*tmp_right_pos;
  /* Pointers that are used as limits (begin and end of the field buffer) */
  uchar *left_wall,*right_wall;
  uchar tmp_char;
  /*
    To remember if get_thd()->cuted_fields has already been incremented,
    to do that only once
  */
  bool is_cuted_fields_incr=0;

  /*
    There are three steps in this function :
    - parse the input string
    - modify the position of digits around the decimal dot '.' 
      according to the exponent value (if specified)
    - write the formatted number
  */

  if ((tmp_dec=dec))
    tmp_dec++;

  /* skip pre-space */
  while (from != end && my_isspace(&my_charset_bin,*from))
    from++;
  if (from == end)
  {
    set_warning(WARN_DATA_TRUNCATED, 1);
    is_cuted_fields_incr=1;
  }
  else if (*from == '+' || *from == '-')	// Found some sign ?
  {
    sign_char= *from++;
    /*
      We allow "+" for unsigned decimal unless defined different
      Both options allowed as one may wish not to have "+" for unsigned numbers
      because of data processing issues
    */ 
    if (unsigned_flag)  
    { 
      if (sign_char=='-')
      {
        Field_decimal::overflow(1);
        return 1;
      }
      /* 
	 Defining this will not store "+" for unsigned decimal type even if
	 it is passed in numeric string. This will make some tests to fail
      */	 
#ifdef DONT_ALLOW_UNSIGNED_PLUS      
      else 
        sign_char=0;
#endif 	
    }
  }

  pre_zeros_from= from;
  for (; from!=end && *from == '0'; from++) ;	// Read prezeros
  pre_zeros_end=int_digits_from=from;      
  /* Read non zero digits at the left of '.'*/
  for (; from != end && my_isdigit(&my_charset_bin, *from) ; from++) ;
  int_digits_end=from;
  if (from!=end && *from == '.')		// Some '.' ?
    from++;
  frac_digits_from= from;
  /* Read digits at the right of '.' */
  for (;from!=end && my_isdigit(&my_charset_bin, *from); from++) ;
  frac_digits_end=from;
  // Some exponentiation symbol ?
  if (from != end && (*from == 'e' || *from == 'E'))
  {   
    from++;
    if (from != end && (*from == '+' || *from == '-'))  // Some exponent sign ?
      expo_sign_char= *from++;
    else
      expo_sign_char= '+';
    /*
      Read digits of the exponent and compute its value.  We must care about
      'exponent' overflow, because as unsigned arithmetic is "modulo", big 
      exponents will become small (e.g. 1e4294967296 will become 1e0, and the 
      field will finally contain 1 instead of its max possible value).
    */
    for (;from!=end && my_isdigit(&my_charset_bin, *from); from++)
    {
      exponent=10*exponent+(*from-'0');
      if (exponent>MAX_EXPONENT)
        break;
    }
  }
  
  /*
    We only have to generate warnings if count_cuted_fields is set.
    This is to avoid extra checks of the number when they are not needed.
    Even if this flag is not set, it's OK to increment warnings, if
    it makes the code easier to read.
  */

  if (get_thd()->count_cuted_fields > CHECK_FIELD_EXPRESSION)
  {
    // Skip end spaces
    for (;from != end && my_isspace(&my_charset_bin, *from); from++) ;
    if (from != end)                     // If still something left, warn
    {
      set_warning(WARN_DATA_TRUNCATED, 1);
      is_cuted_fields_incr=1;
    }
  }
  
  /*
    Now "move" digits around the decimal dot according to the exponent value,
    and add necessary zeros.
    Examples :
    - 1E+3 : needs 3 more zeros at the left of '.' (int_digits_added_zeros=3)
    - 1E-3 : '1' moves at the right of '.', and 2 more zeros are needed
    between '.' and '1'
    - 1234.5E-3 : '234' moves at the right of '.'
    These moves are implemented with pointers which point at the begin
    and end of each moved segment. Examples :
    - 1234.5E-3 : before the code below is executed, the int_digits part is
    from '1' to '4' and the frac_digits part from '5' to '5'. After the code
    below, the int_digits part is from '1' to '1', the frac_digits_head
    part is from '2' to '4', and the frac_digits part from '5' to '5'.
    - 1234.5E3 : before the code below is executed, the int_digits part is
    from '1' to '4' and the frac_digits part from '5' to '5'. After the code
    below, the int_digits part is from '1' to '4', the int_digits_tail
    part is from '5' to '5', the frac_digits part is empty, and
    int_digits_added_zeros=2 (to make 1234500).
  */
  
  /* 
     Below tmp_uint cannot overflow with small enough MAX_EXPONENT setting,
     as int_digits_added_zeros<=exponent<4G and 
     (int_digits_end-int_digits_from)<=max_allowed_packet<=2G and
     (frac_digits_from-int_digits_tail_from)<=max_allowed_packet<=2G
  */

  if (!expo_sign_char)
    tmp_uint=tmp_dec+(uint)(int_digits_end-int_digits_from);
  else if (expo_sign_char == '-') 
  {
    tmp_uint=MY_MIN(exponent,(uint)(int_digits_end-int_digits_from));
    frac_digits_added_zeros=exponent-tmp_uint;
    int_digits_end -= tmp_uint;
    frac_digits_head_end=int_digits_end+tmp_uint;
    tmp_uint=tmp_dec+(uint)(int_digits_end-int_digits_from);     
  }
  else // (expo_sign_char=='+') 
  {
    tmp_uint=MY_MIN(exponent,(uint)(frac_digits_end-frac_digits_from));
    int_digits_added_zeros=exponent-tmp_uint;
    int_digits_tail_from=frac_digits_from;
    frac_digits_from=frac_digits_from+tmp_uint;
    /*
      We "eat" the heading zeros of the 
      int_digits.int_digits_tail.int_digits_added_zeros concatenation
      (for example 0.003e3 must become 3 and not 0003)
    */
    if (int_digits_from == int_digits_end) 
    {
      /*
	There was nothing in the int_digits part, so continue
	eating int_digits_tail zeros
      */
      for (; int_digits_tail_from != frac_digits_from &&
	     *int_digits_tail_from == '0'; int_digits_tail_from++) ;
      if (int_digits_tail_from == frac_digits_from) 
      {
	// there were only zeros in int_digits_tail too
	int_digits_added_zeros=0;
      }
    }
    tmp_uint= (uint) (tmp_dec+(int_digits_end-int_digits_from)+
               (uint)(frac_digits_from-int_digits_tail_from)+
               int_digits_added_zeros);
  }
  
  /*
    Now write the formatted number
    
    First the digits of the int_% parts.
    Do we have enough room to write these digits ?
    If the sign is defined and '-', we need one position for it
  */

  if (field_length < tmp_uint + (int) (sign_char == '-')) 
  {
    // too big number, change to max or min number
    Field_decimal::overflow(sign_char == '-');
    return 1;
  }
 
  /*
    Tmp_left_pos is the position where the leftmost digit of
    the int_% parts will be written
  */
  tmp_left_pos=pos=to+(uint)(field_length-tmp_uint);
  
  // Write all digits of the int_% parts
  while (int_digits_from != int_digits_end)
    *pos++ = *int_digits_from++ ;

  if (expo_sign_char == '+')
  {    
    while (int_digits_tail_from != frac_digits_from)
      *pos++= *int_digits_tail_from++;
    while (int_digits_added_zeros-- >0)
      *pos++= '0';  
  }
  /*
    Note the position where the rightmost digit of the int_% parts has been
    written (this is to later check if the int_% parts contained nothing,
    meaning an extra 0 is needed).
  */
  tmp_right_pos=pos;

  /*
    Step back to the position of the leftmost digit of the int_% parts,
    to write sign and fill with zeros or blanks or prezeros.
  */
  pos=tmp_left_pos-1;
  if (zerofill)
  {
    left_wall=to-1;
    while (pos > left_wall)			// Fill with zeros
      *pos--='0';
  }
  else
  {
    left_wall=to+(sign_char != 0)-1;
    if (!expo_sign_char)	// If exponent was specified, ignore prezeros
    {
      for (;pos > left_wall && pre_zeros_from !=pre_zeros_end;
	   pre_zeros_from++)
	*pos--= '0';
    }
    if (pos == tmp_right_pos-1)
      *pos--= '0';		// no 0 has ever been written, so write one
    left_wall= to-1;
    if (sign_char && pos != left_wall)
    {
      /* Write sign if possible (it is if sign is '-') */
      *pos--= sign_char;
    }
    while (pos != left_wall)
      *pos--=' ';  //fill with blanks
  }
  
  /*
    Write digits of the frac_% parts ;
    Depending on get_thd()->count_cuted_fields, we may also want
    to know if some non-zero tail of these parts will
    be truncated (for example, 0.002->0.00 will generate a warning,
    while 0.000->0.00 will not)
    (and 0E1000000000 will not, while 1E-1000000000 will)
  */
      
  pos=to+(uint)(field_length-tmp_dec);	// Calculate post to '.'
  right_wall=to+field_length;
  if (pos != right_wall) 
    *pos++='.';

  if (expo_sign_char == '-')
  {
    while (frac_digits_added_zeros-- > 0)
    {
      if (pos == right_wall) 
      {
        if (get_thd()->count_cuted_fields > CHECK_FIELD_EXPRESSION &&
            !is_cuted_fields_incr)
          break; // Go on below to see if we lose non zero digits
        return 0;
      }
      *pos++='0';
    }
    while (int_digits_end != frac_digits_head_end)
    {
      tmp_char= *int_digits_end++;
      if (pos == right_wall)
      {
        if (tmp_char != '0')			// Losing a non zero digit ?
        {
          if (!is_cuted_fields_incr)
            set_warning(WARN_DATA_TRUNCATED, 1);
          return 0;
        }
        continue;
      }
      *pos++= tmp_char;
    }
  }

  for (;frac_digits_from!=frac_digits_end;) 
  {
    tmp_char= *frac_digits_from++;
    if (pos == right_wall)
    {
      if (tmp_char != '0')			// Losing a non zero digit ?
      {
        if (!is_cuted_fields_incr)
        {
          /*
            This is a note, not a warning, as we don't want to abort
            when we cut decimals in strict mode
          */
	  set_note(WARN_DATA_TRUNCATED, 1);
        }
        return 0;
      }
      continue;
    }
    *pos++= tmp_char;
  }
      
  while (pos != right_wall)
   *pos++='0';			// Fill with zeros at right of '.'
  return 0;
}


int Field_decimal::store(double nr)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  if (unsigned_flag && nr < 0)
  {
    overflow(1);
    return 1;
  }
  
  if (!std::isfinite(nr)) // Handle infinity as special case
  {
    overflow(nr < 0.0);
    return 1;
  }

  size_t length;
  uchar fyllchar,*to;
  char buff[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];

  fyllchar = zerofill ? (char) '0' : (char) ' ';
  length= my_fcvt(nr, dec, buff, NULL);

  if (length > field_length)
  {
    overflow(nr < 0.0);
    return 1;
  }
  else
  {
    to=ptr;
    for (size_t i=field_length-length ; i-- > 0 ;)
      *to++ = fyllchar;
    memcpy(to,buff,length);
    return 0;
  }
}


int Field_decimal::store(longlong nr, bool unsigned_val)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  char buff[22];
  uint length, int_part;
  char fyllchar;
  uchar *to;

  if (nr < 0 && unsigned_flag && !unsigned_val)
  {
    overflow(1);
    return 1;
  }
  length= (uint) (longlong10_to_str(nr,buff,unsigned_val ? 10 : -10) - buff);
  int_part= field_length- (dec  ? dec+1 : 0);

  if (length > int_part)
  {
    overflow(!unsigned_val && nr < 0L);		/* purecov: inspected */
    return 1;
  }

  fyllchar = zerofill ? (char) '0' : (char) ' ';
  to= ptr;
  for (uint i=int_part-length ; i-- > 0 ;)
    *to++ = fyllchar;
  memcpy(to,buff,length);
  if (dec)
  {
    to[length]='.';
    bfill(to+length+1,dec,'0');
  }
  return 0;
}


double Field_decimal::val_real(void)
{
  DBUG_ASSERT(marked_for_read());
  int not_used;
  char *end_not_used;
  return my_charset_bin.strntod((char*) ptr, field_length, &end_not_used, &not_used);
}

longlong Field_decimal::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  int not_used;
  if (unsigned_flag)
    return my_charset_bin.strntoull((char*) ptr, field_length, 10, NULL, &not_used);
  return my_charset_bin.strntoll((char*) ptr, field_length, 10, NULL, &not_used);
}


String *Field_decimal::val_str(String *val_buffer __attribute__((unused)),
			       String *val_ptr)
{
  DBUG_ASSERT(marked_for_read());
  uchar *str;
  size_t tmp_length;

  for (str=ptr ; *str == ' ' ; str++) ;
  val_ptr->set_charset(&my_charset_numeric);
  tmp_length= (size_t) (str-ptr);
  if (field_length < tmp_length)		// Error in data
    val_ptr->length(0);
  else
    val_ptr->set_ascii((const char*) str, field_length-tmp_length);
  return val_ptr;
}

/**
  Should be able to handle at least the following fixed decimal formats:
  5.00 , -1.0,  05,  -05, +5 with optional pre/end space
*/

int Field_decimal::cmp(const uchar *a_ptr,const uchar *b_ptr) const
{
  const uchar *end;
  int swap=0;
  /* First remove prefixes '0', ' ', and '-' */
  for (end=a_ptr+field_length;
       a_ptr != end &&
	 (*a_ptr == *b_ptr ||
	  ((my_isspace(&my_charset_bin,*a_ptr)  || *a_ptr == '+' || 
            *a_ptr == '0') &&
	   (my_isspace(&my_charset_bin,*b_ptr) || *b_ptr == '+' || 
            *b_ptr == '0')));
       a_ptr++,b_ptr++)
  {
    if (*a_ptr == '-')				// If both numbers are negative
      swap= -1 ^ 1;				// Swap result      
  }
  if (a_ptr == end)
    return 0;
  if (*a_ptr == '-')
    return -1;
  if (*b_ptr == '-')
    return 1;

  while (a_ptr != end)
  {
    if (*a_ptr++ != *b_ptr++)
      return swap ^ (a_ptr[-1] < b_ptr[-1] ? -1 : 1); // compare digits
  }
  return 0;
}


void Field_decimal::sort_string(uchar *to,uint length)
{
  uchar *str,*end;
  for (str=ptr,end=ptr+length;
       str != end &&
	 ((my_isspace(&my_charset_bin,*str) || *str == '+' ||
	   *str == '0')) ;
       str++)
    *to++=' ';
  if (str == end)
    return;					/* purecov: inspected */

  if (*str == '-')
  {
    *to++=1;					// Smaller than any number
    str++;
    while (str != end)
      if (my_isdigit(&my_charset_bin,*str))
	*to++= (char) ('9' - *str++);
      else
	*to++= *str++;
  }
  else memcpy(to,str,(uint) (end-str));
}


void Field_decimal::sql_type(String &res) const
{
  CHARSET_INFO *cs=res.charset();
  uint tmp=field_length;
  if (!unsigned_flag)
    tmp--;
  if (dec)
    tmp--;
  res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
			  "decimal(%d,%d)/*old*/",tmp,dec));
  add_zerofill_and_unsigned(res);
}


Field *Field_decimal::make_new_field(MEM_ROOT *root, TABLE *new_table,
                                     bool keep_type)
{
  if (keep_type)
    return Field_real::make_new_field(root, new_table, keep_type);

  Field *field= new (root) Field_new_decimal(NULL, field_length,
                                             maybe_null() ? (uchar*) "" : 0, 0,
                                             NONE, &field_name,
                                             dec, flags & ZEROFILL_FLAG,
                                             unsigned_flag);
  if (field)
    field->init_for_make_new_field(new_table, orig_table);
  return field;
}


/****************************************************************************
** Field_new_decimal
****************************************************************************/

static decimal_digits_t get_decimal_precision(uint len, decimal_digits_t dec,
                                              bool unsigned_val)
{
  uint precision= my_decimal_length_to_precision(len, dec, unsigned_val);
  return (decimal_digits_t) MY_MIN(precision, DECIMAL_MAX_PRECISION);
}

Field_new_decimal::Field_new_decimal(uchar *ptr_arg,
                                     uint32 len_arg, uchar *null_ptr_arg,
                                     uchar null_bit_arg,
                                     enum utype unireg_check_arg,
                                     const LEX_CSTRING *field_name_arg,
                                     decimal_digits_t dec_arg,bool zero_arg,
                                     bool unsigned_arg)
  :Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
             unireg_check_arg, field_name_arg,
             MY_MIN(dec_arg, DECIMAL_MAX_SCALE), zero_arg, unsigned_arg)
{
  precision= get_decimal_precision(len_arg, dec_arg, unsigned_arg);
  DBUG_ASSERT(precision <= DECIMAL_MAX_PRECISION);
  DBUG_ASSERT(dec <= DECIMAL_MAX_SCALE);
  bin_size= my_decimal_get_binary_size(precision, dec);
}


int Field_new_decimal::reset(void)
{
  store_value(&decimal_zero);
  return 0;
}


/**
  Generate max/min decimal value in case of overflow.

  @param decimal_value     buffer for value
  @param sign              sign of value which caused overflow
*/

void Field_new_decimal::set_value_on_overflow(my_decimal *decimal_value,
                                              bool sign)
{
  DBUG_ENTER("Field_new_decimal::set_value_on_overflow");
  max_my_decimal(decimal_value, precision, decimals());
  if (sign)
  {
    if (unsigned_flag)
      my_decimal_set_zero(decimal_value);
    else
      decimal_value->sign(TRUE);
  }
  DBUG_VOID_RETURN;
}


/**
  Store decimal value in the binary buffer.

  Checks if decimal_value fits into field size.
  If it does, stores the decimal in the buffer using binary format.
  Otherwise sets maximal number that can be stored in the field.

  @param       decimal_value   my_decimal
  @param [OUT] native_error    the error returned by my_decimal::to_binary().

  @retval
    0 ok
  @retval
    1 error
*/

bool Field_new_decimal::store_value(const my_decimal *decimal_value,
                                    int *native_error)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int error= 0;
  DBUG_ENTER("Field_new_decimal::store_value");
#ifdef DBUG_TRACE
  {
    char dbug_buff[DECIMAL_MAX_STR_LENGTH+2];
    DBUG_PRINT("enter", ("value: %s", dbug_decimal_as_string(dbug_buff, decimal_value)));
  }
#endif

  /* check that we do not try to write negative value in unsigned field */
  if (unsigned_flag && decimal_value->sign())
  {
    DBUG_PRINT("info", ("unsigned overflow"));
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
    error= 1;
    decimal_value= &decimal_zero;
  }
#ifdef DBUG_TRACE
  {
    char dbug_buff[DECIMAL_MAX_STR_LENGTH+2];
    DBUG_PRINT("info", ("saving with precision %d  scale: %d  value %s",
                        (int)precision, (int)dec,
                        dbug_decimal_as_string(dbug_buff, decimal_value)));
  }
#endif

  *native_error= decimal_value->to_binary(ptr, precision, dec,
                                          E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW);

  if (unlikely(*native_error == E_DEC_OVERFLOW))
  {
    my_decimal buff;
    DBUG_PRINT("info", ("overflow"));
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
    set_value_on_overflow(&buff, decimal_value->sign());
    buff.to_binary(ptr, precision, dec);
    error= 1;
  }
  DBUG_EXECUTE("info", print_decimal_buff(decimal_value, (uchar *) ptr,
                                          bin_size););
  DBUG_RETURN(error);
}


bool Field_new_decimal::store_value(const my_decimal *decimal_value)
{
  int native_error;
  bool rc= store_value(decimal_value, &native_error);
  if (unlikely(!rc && native_error == E_DEC_TRUNCATED))
    set_note(WARN_DATA_TRUNCATED, 1);
  return rc;
}


int Field_new_decimal::store(const char *from, size_t length,
                             CHARSET_INFO *charset_arg)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  my_decimal decimal_value;
  THD *thd= get_thd();
  DBUG_ENTER("Field_new_decimal::store(char*)");

  const char *end;
  int err= str2my_decimal(E_DEC_FATAL_ERROR &
                          ~(E_DEC_OVERFLOW | E_DEC_BAD_NUM),
                           from, length, charset_arg,
                           &decimal_value, &end);

  if (err == E_DEC_OVERFLOW) // Too many digits (>81) in the integer part
  {
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
    if (!thd->abort_on_warning)
    {
      set_value_on_overflow(&decimal_value, decimal_value.sign());
      store_decimal(&decimal_value);
    }
    DBUG_RETURN(1);
  }

  if (thd->count_cuted_fields > CHECK_FIELD_EXPRESSION)
  {
    if (check_edom_and_important_data_truncation("decimal",
                                                 err && err != E_DEC_TRUNCATED,
                                                 charset_arg,
                                                 from, length, end))
    {
      if (!thd->abort_on_warning)
      {
        if (err && err != E_DEC_TRUNCATED)
        {
          /*
            If check_decimal() failed because of EDOM-alike error,
            (e.g. E_DEC_BAD_NUM), we have to initialize decimal_value to zero.
            Note: if check_decimal() failed because of truncation,
            decimal_value is already properly initialized.
          */
          my_decimal_set_zero(&decimal_value);
          /*
            TODO: check str2my_decimal() with HF. It seems to do
            decimal_make_zero() on fatal errors, so my_decimal_set_zero()
            is probably not needed here.
          */
        }
        store_decimal(&decimal_value);
      }
      DBUG_RETURN(1);
    }
  }

#ifdef DBUG_TRACE
  char dbug_buff[DECIMAL_MAX_STR_LENGTH+2];
  DBUG_PRINT("enter", ("value: %s",
                       dbug_decimal_as_string(dbug_buff, &decimal_value)));
#endif
  int err2;
  if (store_value(&decimal_value, &err2))
    DBUG_RETURN(1);

  /*
    E_DEC_TRUNCATED means minor truncation, a note should be enough:
    - in err: str2my_decimal() truncated '1e-1000000000000' to 0.0
    - in err2: store_value() truncated 1.123 to 1.12, e.g. for DECIMAL(10,2)
    Also, we send a note if a string had some trailing spaces: '1.12 '
  */
  if (thd->count_cuted_fields > CHECK_FIELD_EXPRESSION &&
      (err == E_DEC_TRUNCATED ||
       err2 == E_DEC_TRUNCATED ||
       end < from + length))
    set_note(WARN_DATA_TRUNCATED, 1);
  DBUG_RETURN(0);
}


/**
  @todo
  Fix following when double2my_decimal when double2decimal
  will return E_DEC_TRUNCATED always correctly
*/

int Field_new_decimal::store(double nr)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  my_decimal decimal_value;
  int err;
  THD *thd= get_thd();
  DBUG_ENTER("Field_new_decimal::store(double)");

  err= double2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW, nr,
                         &decimal_value);
  if (err)
  {
    if (check_overflow(err))
      set_value_on_overflow(&decimal_value, decimal_value.sign());
    /* Only issue a warning if store_value doesn't issue an warning */
    thd->got_warning= 0;
  }
  if (store_value(&decimal_value))
    err= 1;
  else if (err && !thd->got_warning)
    err= warn_if_overflow(err);
  DBUG_RETURN(err);
}


int Field_new_decimal::store(longlong nr, bool unsigned_val)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  my_decimal decimal_value;
  int err;

  if ((err= int2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW,
                           nr, unsigned_val, &decimal_value)))
  {
    if (check_overflow(err))
      set_value_on_overflow(&decimal_value, decimal_value.sign());
    /* Only issue a warning if store_value doesn't issue an warning */
    get_thd()->got_warning= 0;
  }
  if (store_value(&decimal_value))
    err= 1;
  else if (err && !get_thd()->got_warning)
    err= warn_if_overflow(err);
  return err;
}


int Field_new_decimal::store_decimal(const my_decimal *decimal_value)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  return store_value(decimal_value);
}


int Field_new_decimal::store_time_dec(const MYSQL_TIME *ltime, uint dec_arg)
{
  my_decimal decimal_value;
  return store_value(date2my_decimal(ltime, &decimal_value));
}


my_decimal* Field_new_decimal::val_decimal(my_decimal *decimal_value)
{
  DBUG_ASSERT(marked_for_read());
  DBUG_ENTER("Field_new_decimal::val_decimal");
  binary2my_decimal(E_DEC_FATAL_ERROR, ptr, decimal_value,
                    precision, dec);
  DBUG_EXECUTE("info", print_decimal_buff(decimal_value, (uchar *) ptr,
                                          bin_size););
  DBUG_RETURN(decimal_value);
}


int Field_new_decimal::cmp(const uchar *a,const uchar*b) const
{
  return memcmp(a, b, bin_size);
}


void Field_new_decimal::sort_string(uchar *buff, uint length)
{
  memcpy(buff, ptr, length);
}


void Field_new_decimal::sql_type(String &str) const
{
  CHARSET_INFO *cs= str.charset();
  str.length(cs->cset->snprintf(cs, (char*) str.ptr(), str.alloced_length(),
                                "decimal(%d,%d)", precision, (int)dec));
  add_zerofill_and_unsigned(str);
}


/**
   Save the field metadata for new decimal fields.

   Saves the precision in the first byte and decimals() in the second
   byte of the field metadata array at index of *metadata_ptr and 
   *(metadata_ptr + 1).

   @param   metadata_ptr   First byte of field metadata

   @returns number of bytes written to metadata_ptr
*/

Binlog_type_info Field_new_decimal::binlog_type_info() const
{
  DBUG_ASSERT(Field_new_decimal::type() == binlog_type());
  return Binlog_type_info(Field_new_decimal::type(), precision +
                          (decimals() << 8), 2, binlog_signedness());
}


/**
   Returns the number of bytes field uses in row-based replication 
   row packed size.

   This method is used in row-based replication to determine the number
   of bytes that the field consumes in the row record format. This is
   used to skip fields in the master that do not exist on the slave.

   @param   field_metadata   Encoded size in field metadata

   @returns The size of the field based on the field metadata.
*/
uint Field_new_decimal::pack_length_from_metadata(uint field_metadata) const
{
  uint const source_precision= (field_metadata >> 8U) & 0x00ff;
  uint const source_decimal= field_metadata & 0x00ff; 
  uint const source_size= my_decimal_get_binary_size(source_precision, 
                                                     source_decimal);
  return (source_size);
}


bool Field_new_decimal::compatible_field_size(uint field_metadata,
                                              const Relay_log_info * __attribute__((unused)),
                                              uint16 mflags __attribute__((unused)),
                                              int *order_var) const
{
  uint const source_precision= (field_metadata >> 8U) & 0x00ff;
  uint const source_decimal= field_metadata & 0x00ff; 
  int order= compare(source_precision, precision);
  *order_var= order != 0 ? order : compare(source_decimal, dec);
  return true;
}


bool Field_new_decimal::is_equal(const Column_definition &new_field) const
{
  return ((new_field.type_handler() == type_handler()) &&
          ((new_field.flags & UNSIGNED_FLAG) ==
           (uint) (flags & UNSIGNED_FLAG)) &&
          ((new_field.flags & AUTO_INCREMENT_FLAG) <=
           (uint) (flags & AUTO_INCREMENT_FLAG)) &&
          (new_field.length == max_display_length()) &&
          (new_field.decimals == dec));
}


/**
   Unpack a decimal field from row data.

   This method is used to unpack a decimal or numeric field from a master
   whose size of the field is less than that of the slave.
  
   @param   to         Destination of the data
   @param   from       Source of the data
   @param   param_data Precision (upper) and decimal (lower) values

   @return  New pointer into memory based on from + length of the data
*/
const uchar *
Field_new_decimal::unpack(uchar* to, const uchar *from, const uchar *from_end,
                          uint param_data)
{
  if (param_data == 0)
    return Field::unpack(to, from, from_end, param_data);

  uint from_precision= (param_data & 0xff00) >> 8U;
  uint from_decimal= param_data & 0x00ff;
  uint length=pack_length();
  uint from_pack_len= my_decimal_get_binary_size(from_precision, from_decimal);
  uint len= (param_data && (from_pack_len < length)) ?
            from_pack_len : length;
  if ((from_pack_len && (from_pack_len < length)) ||
      (from_precision < precision) ||
      (from_decimal < decimals()))
  {
    /*
      If the master's data is smaller than the slave, we need to convert
      the binary to decimal then resize the decimal converting it back to
      a decimal and write that to the raw data buffer.
    */
    decimal_digit_t dec_buf[DECIMAL_MAX_PRECISION];
    decimal_t dec_val;
    dec_val.len= from_precision;
    dec_val.buf= dec_buf;
    /*
      Note: bin2decimal does not change the length of the field. So it is
      just the first step the resizing operation. The second step does the
      resizing using the precision and decimals from the slave.
    */
    bin2decimal((uchar *)from, &dec_val, from_precision, from_decimal);
    decimal2bin(&dec_val, to, precision, decimals());
  }
  else
  {
    if (from + len > from_end)
      return 0;                                 // Wrong data
    memcpy(to, from, len); // Sizes are the same, just copy the data.
  }
  return from+len;
}


Item *Field_new_decimal::get_equal_const_item(THD *thd, const Context &ctx,
                                              Item *const_item)
{
  if (flags & ZEROFILL_FLAG)
    return Field_num::get_equal_zerofill_const_item(thd, ctx, const_item);
  switch (ctx.subst_constraint()) {
  case IDENTITY_SUBST:
    if (const_item->field_type() != MYSQL_TYPE_NEWDECIMAL ||
        const_item->decimal_scale() != decimals())
    {
      VDec val(const_item);
      if (val.is_null())
      {
        DBUG_ASSERT(0);
        return const_item;
      }
      /*
        Truncate or extend the decimal value to the scale of the field.
        See comments about truncation in the same place in
        Field_time::get_equal_const_item().
      */
      my_decimal tmp;
      val.round_to(&tmp, decimals(), TRUNCATE);
      return new (thd->mem_root) Item_decimal(thd, field_name.str, &tmp,
                                              decimals(), field_length);
    }
    break;
  case ANY_SUBST:
    break;
  }
  return const_item;
}


int Field_int::store_time_dec(const MYSQL_TIME *ltime, uint dec_arg)
{
  longlong v= TIME_to_ulonglong(ltime);
  if (ltime->neg == 0)
    return store(v, true);
  return store(-v, false);
}


void Field_int::sql_type(String &res) const
{
  CHARSET_INFO *cs=res.charset();
  Name name= type_handler()->type_handler_signed()->name();
  res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
			  "%.*s(%d)", (int) name.length(), name.ptr(),
			  (int) field_length));
  add_zerofill_and_unsigned(res);
}


/****************************************************************************
** tiny int
****************************************************************************/

int Field_tiny::store(const char *from,size_t len,CHARSET_INFO *cs)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int error;
  longlong rnd;
  
  error= get_int(cs, from, len, &rnd, 255, -128, 127);
  ptr[0]= unsigned_flag ? (char) (ulonglong) rnd : (char) rnd;
  return error;
}


int Field_tiny::store(double nr)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int error= 0;
  nr=rint(nr);
  if (unsigned_flag)
  {
    if (nr < 0.0)
    {
      *ptr=0;
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else if (nr > 255.0)
    {
      *ptr= (uchar) 255;
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else
      *ptr= (uchar) nr;
  }
  else
  {
    if (nr < -128.0)
    {
      *ptr= (uchar) -128;
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else if (nr > 127.0)
    {
      *ptr=127;
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else
      *ptr=(uchar) (int) nr;
  }
  return error;
}


int Field_tiny::store(longlong nr, bool unsigned_val)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int error= 0;

  if (unsigned_flag)
  {
    if (nr < 0 && !unsigned_val)
    {
      *ptr= 0;
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else if ((ulonglong) nr > (ulonglong) 255)
    {
      *ptr= (char) 255;
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else
      *ptr=(char) nr;
  }
  else
  {
    if (nr < 0 && unsigned_val)
      nr= 256;                                    // Generate overflow
    if (nr < -128)
    {
      *ptr= (char) -128;
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else if (nr > 127)
    {
      *ptr=127;
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else
      *ptr=(char) nr;
  }
  return error;
}


double Field_tiny::val_real(void)
{
  DBUG_ASSERT(marked_for_read());
  int tmp= unsigned_flag ? (int) ptr[0] :
    (int) ((signed char*) ptr)[0];
  return (double) tmp;
}


longlong Field_tiny::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  int tmp= unsigned_flag ? (int) ptr[0] :
    (int) ((signed char*) ptr)[0];
  return (longlong) tmp;
}


String *Field_tiny::val_str(String *val_buffer,
			    String *val_ptr __attribute__((unused)))
{
  DBUG_ASSERT(marked_for_read());
  long nr= unsigned_flag ? (long) ptr[0] : (long) ((signed char*) ptr)[0];
  return val_str_from_long(val_buffer, 5, -10, nr);
}

bool Field_tiny::send(Protocol *protocol)
{
  DBUG_ASSERT(marked_for_read());
  Protocol_text *txt;
  if (unlikely(zerofill) && (txt= dynamic_cast<Protocol_text*>(protocol)))
    return send_numeric_zerofill_str(txt, PROTOCOL_SEND_TINY);
  return protocol->store_tiny(Field_tiny::val_int());
}


int Field_tiny::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  signed char a,b;
  a=(signed char) a_ptr[0]; b= (signed char) b_ptr[0];
  if (unsigned_flag)
    return ((uchar) a < (uchar) b) ? -1 : ((uchar) a > (uchar) b) ? 1 : 0;
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

void Field_tiny::sort_string(uchar *to,uint length __attribute__((unused)))
{
  if (unsigned_flag)
    *to= *ptr;
  else
    to[0] = (char) (ptr[0] ^ (uchar) 128);	/* Revers signbit */
}

/****************************************************************************
 Field type short int (2 byte)
****************************************************************************/

int Field_short::store(const char *from,size_t len,CHARSET_INFO *cs)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int store_tmp;
  int error;
  longlong rnd;
  
  error= get_int(cs, from, len, &rnd, UINT_MAX16, INT_MIN16, INT_MAX16);
  store_tmp= unsigned_flag ? (int) (ulonglong) rnd : (int) rnd;
  int2store(ptr, store_tmp);
  return error;
}


int Field_short::store(double nr)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int error= 0;
  int16 res;
  nr=rint(nr);
  if (unsigned_flag)
  {
    if (nr < 0)
    {
      res=0;
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else if (nr > (double) UINT_MAX16)
    {
      res=(int16) UINT_MAX16;
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else
      res=(int16) (uint16) nr;
  }
  else
  {
    if (nr < (double) INT_MIN16)
    {
      res=INT_MIN16;
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else if (nr > (double) INT_MAX16)
    {
      res=INT_MAX16;
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else
      res=(int16) (int) nr;
  }
  int2store(ptr,res);
  return error;
}


int Field_short::store(longlong nr, bool unsigned_val)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int error= 0;
  int16 res;

  if (unsigned_flag)
  {
    if (nr < 0L && !unsigned_val)
    {
      res=0;
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else if ((ulonglong) nr > (ulonglong) UINT_MAX16)
    {
      res=(int16) UINT_MAX16;
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else
      res=(int16) (uint16) nr;
  }
  else
  {
    if (nr < 0 && unsigned_val)
      nr= UINT_MAX16+1;                         // Generate overflow

    if (nr < INT_MIN16)
    {
      res=INT_MIN16;
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else if (nr > (longlong) INT_MAX16)
    {
      res=INT_MAX16;
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else
      res=(int16) nr;
  }
  int2store(ptr,res);
  return error;
}


double Field_short::val_real(void)
{
  DBUG_ASSERT(marked_for_read());
  short j;
  j=sint2korr(ptr);
  return unsigned_flag ? (double) (unsigned short) j : (double) j;
}

longlong Field_short::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  short j;
  j=sint2korr(ptr);
  return unsigned_flag ? (longlong) (unsigned short) j : (longlong) j;
}


String *Field_short::val_str(String *val_buffer,
			     String *val_ptr __attribute__((unused)))
{
  DBUG_ASSERT(marked_for_read());
  short j= sint2korr(ptr);
  long nr= unsigned_flag ? (long) (unsigned short) j : (long) j;
  return val_str_from_long(val_buffer, 7, -10, nr);
}


bool Field_short::send(Protocol *protocol)
{
  DBUG_ASSERT(marked_for_read());
  Protocol_text *txt;
  if (unlikely(zerofill) && (txt= dynamic_cast<Protocol_text*>(protocol)))
    return send_numeric_zerofill_str(txt, PROTOCOL_SEND_SHORT);
  return protocol->store_short(Field_short::val_int());
}


int Field_short::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  short a,b;
  a=sint2korr(a_ptr);
  b=sint2korr(b_ptr);

  if (unsigned_flag)
    return ((unsigned short) a < (unsigned short) b) ? -1 :
    ((unsigned short) a > (unsigned short) b) ? 1 : 0;
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

void Field_short::sort_string(uchar *to,uint length __attribute__((unused)))
{
  if (unsigned_flag)
    to[0] = ptr[1];
  else
    to[0] = (char) (ptr[1] ^ 128);              /* Revers signbit */
  to[1]   = ptr[0];
}

/****************************************************************************
  Field type medium int (3 byte)
****************************************************************************/

int Field_medium::store(const char *from,size_t len,CHARSET_INFO *cs)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int store_tmp;
  int error;
  longlong rnd;
  
  error= get_int(cs, from, len, &rnd, UINT_MAX24, INT_MIN24, INT_MAX24);
  store_tmp= unsigned_flag ? (int) (ulonglong) rnd : (int) rnd;
  int3store(ptr, store_tmp);
  return error;
}


int Field_medium::store(double nr)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int error= 0;
  nr=rint(nr);
  if (unsigned_flag)
  {
    if (nr < 0)
    {
      int3store(ptr,0);
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else if (nr >= (double) (long) (1L << 24))
    {
      uint32 tmp=(uint32) (1L << 24)-1L;
      int3store(ptr,tmp);
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else
      int3store(ptr,(uint32) nr);
  }
  else
  {
    if (nr < (double) INT_MIN24)
    {
      long tmp=(long) INT_MIN24;
      int3store(ptr,tmp);
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else if (nr > (double) INT_MAX24)
    {
      long tmp=(long) INT_MAX24;
      int3store(ptr,tmp);
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else
      int3store(ptr,(long) nr);
  }
  return error;
}


int Field_medium::store(longlong nr, bool unsigned_val)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int error= 0;

  if (unsigned_flag)
  {
    if (nr < 0 && !unsigned_val)
    {
      int3store(ptr,0);
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else if ((ulonglong) nr >= (ulonglong) (long) (1L << 24))
    {
      long tmp= (long) (1L << 24)-1L;
      int3store(ptr,tmp);
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else
      int3store(ptr,(uint32) nr);
  }
  else
  {
    if (nr < 0 && unsigned_val)
      nr= (ulonglong) (long) (1L << 24);        // Generate overflow

    if (nr < (longlong) INT_MIN24)
    {
      long tmp= (long) INT_MIN24;
      int3store(ptr,tmp);
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else if (nr > (longlong) INT_MAX24)
    {
      long tmp=(long) INT_MAX24;
      int3store(ptr,tmp);
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else
      int3store(ptr,(long) nr);
  }
  return error;
}


double Field_medium::val_real(void)
{
  DBUG_ASSERT(marked_for_read());
  long j= unsigned_flag ? (long) uint3korr(ptr) : sint3korr(ptr);
  return (double) j;
}


longlong Field_medium::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  long j= unsigned_flag ? (long) uint3korr(ptr) : sint3korr(ptr);
  return (longlong) j;
}


String *Field_medium::val_str(String *val_buffer,
			      String *val_ptr __attribute__((unused)))
{
  DBUG_ASSERT(marked_for_read());
  long nr= unsigned_flag ? (long) uint3korr(ptr) : sint3korr(ptr);
  return val_str_from_long(val_buffer, 10, -10, nr);
}


String *Field_int::val_str_from_long(String *val_buffer,
                                     uint max_char_length,
                                     int radix, long nr)
{
  CHARSET_INFO *cs= &my_charset_numeric;
  uint length;
  uint mlength= MY_MAX(field_length + 1, max_char_length * cs->mbmaxlen);
  val_buffer->alloc(mlength);
  char *to=(char*) val_buffer->ptr();
  length= (uint) cs->long10_to_str(to, mlength, radix, nr);
  val_buffer->length(length);
  if (zerofill)
    prepend_zeros(val_buffer); /* purecov: inspected */
  val_buffer->set_charset(cs);
  return val_buffer;
}


bool Field_medium::send(Protocol *protocol)
{
  DBUG_ASSERT(marked_for_read());
  Protocol_text *txt;
  if (unlikely(zerofill) && (txt= dynamic_cast<Protocol_text*>(protocol)))
    return send_numeric_zerofill_str(txt, PROTOCOL_SEND_LONG);
  return protocol->store_long(Field_medium::val_int());
}


int Field_medium::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  long a,b;
  if (unsigned_flag)
  {
    a=uint3korr(a_ptr);
    b=uint3korr(b_ptr);
  }
  else
  {
    a=sint3korr(a_ptr);
    b=sint3korr(b_ptr);
  }
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

void Field_medium::sort_string(uchar *to,uint length __attribute__((unused)))
{
  if (unsigned_flag)
    to[0] = ptr[2];
  else
    to[0] = (uchar) (ptr[2] ^ 128);		/* Revers signbit */
  to[1] = ptr[1];
  to[2] = ptr[0];
}


/****************************************************************************
** long int
****************************************************************************/

int Field_long::store(const char *from,size_t len,CHARSET_INFO *cs)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  long store_tmp;
  int error;
  longlong rnd;
  
  error= get_int(cs, from, len, &rnd, UINT_MAX32, INT_MIN32, INT_MAX32);
  store_tmp= unsigned_flag ? (long) (ulonglong) rnd : (long) rnd;
  int4store(ptr, store_tmp);
  return error;
}


int Field_long::store(double nr)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int error= 0;
  int32 res;
  nr=rint(nr);
  if (unsigned_flag)
  {
    if (nr < 0)
    {
      res=0;
      error= 1;
    }
    else if (nr > (double) UINT_MAX32)
    {
      res= UINT_MAX32;
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
    else
      res=(int32) (ulong) nr;
  }
  else
  {
    if (nr < (double) INT_MIN32)
    {
      res=(int32) INT_MIN32;
      error= 1;
    }
    else if (nr > (double) INT_MAX32)
    {
      res=(int32) INT_MAX32;
      error= 1;
    }
    else
      res=(int32) (longlong) nr;
  }
  if (unlikely(error))
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);

  int4store(ptr,res);
  return error;
}


int Field_long::store(longlong nr, bool unsigned_val)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int error= 0;
  int32 res;

  if (unsigned_flag)
  {
    if (nr < 0 && !unsigned_val)
    {
      res=0;
      error= 1;
    }
    else if ((ulonglong) nr >= (1LL << 32))
    {
      res=(int32) (uint32) ~0L;
      error= 1;
    }
    else
      res=(int32) (uint32) nr;
  }
  else
  {
    if (nr < 0 && unsigned_val)
      nr= ((longlong) INT_MAX32) + 1;           // Generate overflow
    if (nr < (longlong) INT_MIN32) 
    {
      res=(int32) INT_MIN32;
      error= 1;
    }
    else if (nr > (longlong) INT_MAX32)
    {
      res=(int32) INT_MAX32;
      error= 1;
    }
    else
      res=(int32) nr;
  }
  if (unlikely(error))
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);

  int4store(ptr,res);
  return error;
}


double Field_long::val_real(void)
{
  DBUG_ASSERT(marked_for_read());
  int32 j;
  j=sint4korr(ptr);
  return unsigned_flag ? (double) (uint32) j : (double) j;
}

longlong Field_long::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  int32 j;
  /* See the comment in Field_long::store(long long) */
  DBUG_ASSERT(!table || table->in_use == current_thd);
  j=sint4korr(ptr);
  return unsigned_flag ? (longlong) (uint32) j : (longlong) j;
}


String *Field_long::val_str(String *val_buffer,
			    String *val_ptr __attribute__((unused)))
{
  DBUG_ASSERT(marked_for_read());
  long nr= unsigned_flag ? (long) uint4korr(ptr) : sint4korr(ptr);
  return val_str_from_long(val_buffer, 12, unsigned_flag ? 10 : -10, nr);
}


bool Field_long::send(Protocol *protocol)
{
  DBUG_ASSERT(marked_for_read());
  Protocol_text *txt;
  if (unlikely(zerofill) && (txt= dynamic_cast<Protocol_text*>(protocol)))
    return send_numeric_zerofill_str(txt, PROTOCOL_SEND_LONG);
  return protocol->store_long(Field_long::val_int());
}


int Field_long::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  int32 a,b;
  a=sint4korr(a_ptr);
  b=sint4korr(b_ptr);
  if (unsigned_flag)
    return ((uint32) a < (uint32) b) ? -1 : ((uint32) a > (uint32) b) ? 1 : 0;
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

void Field_long::sort_string(uchar *to,uint length __attribute__((unused)))
{
  if (unsigned_flag)
    to[0] = ptr[3];
  else
    to[0] = (char) (ptr[3] ^ 128);              /* Revers signbit */
  to[1]   = ptr[2];
  to[2]   = ptr[1];
  to[3]   = ptr[0];
}


/****************************************************************************
 Field type longlong int (8 bytes)
****************************************************************************/

int Field_longlong::store(const char *from,size_t len,CHARSET_INFO *cs)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int error= 0;
  char *end;
  ulonglong tmp;

  tmp= cs->strntoull10rnd(from, len, unsigned_flag, &end, &error);
  if (unlikely(error == MY_ERRNO_ERANGE))
  {
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
    error= 1;
  }
  else if (get_thd()->count_cuted_fields > CHECK_FIELD_EXPRESSION &&
           check_int(cs, from, len, end, error))
    error= 1;
  else
    error= 0;
  int8store(ptr,tmp);
  return error;
}


int Field_longlong::store(double nr)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  Converter_double_to_longlong conv(nr, unsigned_flag);

  if (unlikely(conv.error()))
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);

  int8store(ptr, conv.result());
  return conv.error();
}


int Field_longlong::store(longlong nr, bool unsigned_val)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int error= 0;

  if (unlikely(nr < 0))                         // Only possible error
  {
    /*
      if field is unsigned and value is signed (< 0) or
      if field is signed and value is unsigned we have an overflow
    */
    if (unsigned_flag != unsigned_val)
    {
      nr= unsigned_flag ? (ulonglong) 0 : (ulonglong) LONGLONG_MAX;
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
  }

  int8store(ptr,nr);
  return error;
}


double Field_longlong::val_real(void)
{
  DBUG_ASSERT(marked_for_read());
  longlong j;
  j=sint8korr(ptr);
  /* The following is open coded to avoid a bug in gcc 3.3 */
  if (unsigned_flag)
  {
    ulonglong tmp= (ulonglong) j;
    return ulonglong2double(tmp);
  }
  return (double) j;
}


longlong Field_longlong::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  longlong j;
  j=sint8korr(ptr);
  return j;
}


String *Field_longlong::val_str(String *val_buffer,
				String *val_ptr __attribute__((unused)))
{
  CHARSET_INFO *cs= &my_charset_numeric;
  uint length;
  uint mlength=MY_MAX(field_length+1,22*cs->mbmaxlen);
  val_buffer->alloc(mlength);
  char *to=(char*) val_buffer->ptr();
  longlong j;
  j=sint8korr(ptr);

  length=(uint) (cs->longlong10_to_str)(to, mlength,
		                        unsigned_flag ? 10 : -10, j);
  val_buffer->length(length);
  if (zerofill)
    prepend_zeros(val_buffer);
  val_buffer->set_charset(cs);
  return val_buffer;
}


bool Field_longlong::send(Protocol *protocol)
{
  DBUG_ASSERT(marked_for_read());
  Protocol_text *txt;
  if (unlikely(zerofill) && (txt= dynamic_cast<Protocol_text*>(protocol)))
    return send_numeric_zerofill_str(txt, PROTOCOL_SEND_LONGLONG);
  return protocol->store_longlong(Field_longlong::val_int(), unsigned_flag);
}


int Field_longlong::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  longlong a,b;
  a=sint8korr(a_ptr);
  b=sint8korr(b_ptr);
  if (unsigned_flag)
    return ((ulonglong) a < (ulonglong) b) ? -1 :
    ((ulonglong) a > (ulonglong) b) ? 1 : 0;
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

void Field_longlong::sort_string(uchar *to,uint length __attribute__((unused)))
{
  if (unsigned_flag)
    to[0] = ptr[7];
  else
    to[0] = (char) (ptr[7] ^ 128);		/* Revers signbit */
  to[1]   = ptr[6];
  to[2]   = ptr[5];
  to[3]   = ptr[4];
  to[4]   = ptr[3];
  to[5]   = ptr[2];
  to[6]   = ptr[1];
  to[7]   = ptr[0];
}


void Field_longlong::set_max()
{
  DBUG_ASSERT(marked_for_write_or_computed());
  set_notnull();
  int8store(ptr, unsigned_flag ? ULONGLONG_MAX : LONGLONG_MAX);
}

bool Field_longlong::is_max()
{
  DBUG_ASSERT(marked_for_read());
  if (unsigned_flag)
  {
    ulonglong j;
    j= uint8korr(ptr);
    return j == ULONGLONG_MAX;
  }
  longlong j;
  j= sint8korr(ptr);
  return j == LONGLONG_MAX;
}

/*
  Floating-point numbers
 */

/****************************************************************************
  single precision float
****************************************************************************/

int Field_float::store(const char *from,size_t len,CHARSET_INFO *cs)
{
  int error;
  Field_float::store(get_double(from, len, cs, &error));
  return error;
}


int Field_float::store(double nr)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int error= truncate_double(&nr, field_length,
                             not_fixed ? NOT_FIXED_DEC : dec,
                             unsigned_flag, FLT_MAX);
  if (unlikely(error))
  {
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
    if (error < 0)                                // Wrong double value
    {
      error= 1;
      set_null();
    }
  }
  float j= (float)nr;

  float4store(ptr,j);
  return error;
}


int Field_float::store(longlong nr, bool unsigned_val)
{
  return Field_float::store(unsigned_val ? ulonglong2double((ulonglong) nr) :
                            (double) nr);
}


double Field_float::val_real(void)
{
  DBUG_ASSERT(marked_for_read());
  float j;
  float4get(j,ptr);
  return ((double) j);
}

longlong Field_float::val_int(void)
{
  float j;
  float4get(j,ptr);
  return Converter_double_to_longlong(j, false).result();
}


String *Field_float::val_str(String *val_buffer,
			     String *val_ptr __attribute__((unused)))
{
  DBUG_ASSERT(marked_for_read());
  DBUG_ASSERT(!zerofill || field_length <= MAX_FIELD_CHARLENGTH);

  if (Float(ptr).to_string(val_buffer, dec))
  {
    my_error(ER_OUT_OF_RESOURCES, MYF(0));
    return val_buffer;
  }

  if (zerofill)
    prepend_zeros(val_buffer);
  return val_buffer;
}


int Field_float::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  float a,b;
  float4get(a,a_ptr);
  float4get(b,b_ptr);
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

#define FLT_EXP_DIG (sizeof(float)*8-FLT_MANT_DIG)

void Field_float::sort_string(uchar *to,uint length __attribute__((unused)))
{
  float nr;
  float4get(nr,ptr);

  uchar *tmp= to;
  if (nr == (float) 0.0)
  {						/* Change to zero string */
    tmp[0]=(uchar) 128;
    bzero((char*) tmp+1,sizeof(nr)-1);
  }
  else
  {
#ifdef WORDS_BIGENDIAN
    memcpy(tmp, &nr, sizeof(nr));
#else
    tmp[0]= ptr[3]; tmp[1]=ptr[2]; tmp[2]= ptr[1]; tmp[3]=ptr[0];
#endif
    if (tmp[0] & 128)				/* Negative */
    {						/* make complement */
      uint i;
      for (i=0 ; i < sizeof(nr); i++)
	tmp[i]= (uchar) (tmp[i] ^ (uchar) 255);
    }
    else
    {
      ushort exp_part=(((ushort) tmp[0] << 8) | (ushort) tmp[1] |
		       (ushort) 32768);
      exp_part+= (ushort) 1 << (16-1-FLT_EXP_DIG);
      tmp[0]= (uchar) (exp_part >> 8);
      tmp[1]= (uchar) exp_part;
    }
  }
}


bool Field_float::send(Protocol *protocol)
{
  DBUG_ASSERT(marked_for_read());
  Protocol_text *txt;
  if (unlikely(zerofill) && (txt= dynamic_cast<Protocol_text*>(protocol)))
    return send_numeric_zerofill_str(txt, PROTOCOL_SEND_FLOAT);
  return protocol->store_float((float) Field_float::val_real(), dec);
}


/**
   Save the field metadata for float fields.

   Saves the pack length in the first byte.

   @param   metadata_ptr   First byte of field metadata

   @returns number of bytes written to metadata_ptr
*/
Binlog_type_info Field_float::binlog_type_info() const
{
  DBUG_ASSERT(Field_float::type() == binlog_type());
  return Binlog_type_info(Field_float::type(), pack_length(), 1,
                          binlog_signedness());
}


/****************************************************************************
  double precision floating point numbers
****************************************************************************/

int Field_double::store(const char *from,size_t len,CHARSET_INFO *cs)
{
  int error;
  Field_double::store(get_double(from, len, cs, &error));
  return error;
}


int Field_double::store(double nr)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int error= truncate_double(&nr, field_length,
                             not_fixed ? NOT_FIXED_DEC : dec,
                             unsigned_flag, DBL_MAX);
  if (unlikely(error))
  {
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
    if (error < 0)                                // Wrong double value
    {
      error= 1;
      set_null();
    }
  }

  float8store(ptr,nr);
  return error;
}


int Field_double::store(longlong nr, bool unsigned_val)
{
  return Field_double::store(unsigned_val ? ulonglong2double((ulonglong) nr) :
                             (double) nr);
}

/*
  If a field has fixed length, truncate the double argument pointed to by 'nr'
  appropriately.
  Also ensure that the argument is within [-max_value; max_value] range.

  return
    0   ok
    -1  Illegal double value
    1   Value was truncated
*/

int truncate_double(double *nr, uint field_length, decimal_digits_t dec,
                    bool unsigned_flag, double max_value)
{
  int error= 0;
  double res= *nr;
  
  if (std::isnan(res))
  {
    *nr= 0;
    return -1;
  }
  else if (unsigned_flag && res < 0)
  {
    *nr= 0;
    return 1;
  }

  if (dec < FLOATING_POINT_DECIMALS)
  {
    uint order= field_length - dec;
    uint step= array_elements(log_10) - 1;
    double max_value_by_dec= 1.0;
    for (; order > step; order-= step)
      max_value_by_dec*= log_10[step];
    max_value_by_dec*= log_10[order];
    max_value_by_dec-= 1.0 / log_10[dec];
    set_if_smaller(max_value, max_value_by_dec);

    /* Check for infinity so we don't get NaN in calculations */
    if (!std::isinf(res))
    {
      double tmp= rint((res - floor(res)) * log_10[dec]) / log_10[dec];
      res= floor(res) + tmp;
    }
  }
  
  if (res < -max_value)
  {
    res= -max_value;
    error= 1;
  }
  else if (res > max_value)
  {
    res= max_value;
    error= 1;
  }

  *nr= res;
  return error;
}

/*
  Convert double to longlong / ulonglong.
  If double is outside of the supported range,
  adjust m_result and set m_error.

  @param nr             Number to convert
  @param unsigned_flag  true if result is unsigned
*/

Value_source::
Converter_double_to_longlong::Converter_double_to_longlong(double nr,
                                                           bool unsigned_flag)
  :m_error(false)
{
  nr= rint(nr);
  if (unsigned_flag)
  {
    if (nr < 0)
    {
      m_result= 0;
      m_error= true;
    }
    else if (nr >= (double) ULONGLONG_MAX)
    {
      m_result= ~(longlong) 0;
      m_error= true;
    }
    else
      m_result= (longlong) double2ulonglong(nr);
  }
  else
  {
    if (nr <= (double) LONGLONG_MIN)
    {
      m_result= LONGLONG_MIN;
      m_error= (nr < (double) LONGLONG_MIN);
    }
    else if (nr >= (double) (ulonglong) LONGLONG_MAX)
    {
      m_result= LONGLONG_MAX;
      m_error= (nr > (double) LONGLONG_MAX);
    }
    else
      m_result= (longlong) nr;
  }
}


void Value_source::
Converter_double_to_longlong::push_warning(THD *thd,
                                           double nr,
                                           bool unsigned_flag)
{
  push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
                      ER_DATA_OVERFLOW, ER_THD(thd, ER_DATA_OVERFLOW),
                      ErrConvDouble(nr).ptr(),
                      unsigned_flag ? "UNSIGNED INT" : "INT");
}


int Field_real::store_time_dec(const MYSQL_TIME *ltime, uint dec_arg)
{
  return store(TIME_to_double(ltime));
}


double Field_double::val_real(void)
{
  DBUG_ASSERT(marked_for_read());
  double j;
  float8get(j,ptr);
  return j;
}


longlong Field_double::val_int_from_real(bool want_unsigned_result)
{
  Converter_double_to_longlong conv(val_real(), want_unsigned_result);
  if (unlikely(!want_unsigned_result && conv.error()))
    conv.push_warning(get_thd(), Field_double::val_real(), false);
  return conv.result();
}


my_decimal *Field_real::val_decimal(my_decimal *decimal_value)
{
  DBUG_ASSERT(marked_for_read());
  double2my_decimal(E_DEC_FATAL_ERROR, val_real(), decimal_value);
  return decimal_value;
}


bool Field_real::get_date(MYSQL_TIME *ltime,date_mode_t fuzzydate)
{
  DBUG_ASSERT(marked_for_read());
  double nr= val_real();
  return double_to_datetime_with_warn(get_thd(), nr, ltime, fuzzydate,
                                      table->s, field_name.str);
}


Item *Field_real::get_equal_const_item(THD *thd, const Context &ctx,
                                       Item *const_item)
{
  if (flags & ZEROFILL_FLAG)
    return Field_num::get_equal_zerofill_const_item(thd, ctx, const_item);
  switch (ctx.subst_constraint()) {
  case IDENTITY_SUBST:
    if (const_item->decimal_scale() != Field_real::decimals())
    {
      double val= const_item->val_real();
      return new (thd->mem_root) Item_float(thd, val, Field_real::decimals());
    }
    break;
  case ANY_SUBST:
    break;
  }
  return const_item;
}


void Field_real::sql_type(String &res) const
{
  const Name name= type_handler()->name();
  if (dec >= FLOATING_POINT_DECIMALS)
  {
    res.set_ascii(name.ptr(), name.length());
  }
  else
  {
    CHARSET_INFO *cs= res.charset();
    res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
			    "%.*s(%d,%d)", (int) name.length(), name.ptr(),
			    (int) field_length,dec));
  }
  add_zerofill_and_unsigned(res);
}


String *Field_double::val_str(String *val_buffer,
			      String *val_ptr __attribute__((unused)))
{
  DBUG_ASSERT(marked_for_read());
  DBUG_ASSERT(!zerofill || field_length <= MAX_FIELD_CHARLENGTH);
  double nr;
  float8get(nr,ptr);

  uint to_length= DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE;
  if (val_buffer->alloc(to_length))
  {
    my_error(ER_OUT_OF_RESOURCES, MYF(0));
    return val_buffer;
  }

  char *to=(char*) val_buffer->ptr();
  size_t len;

  if (dec >= FLOATING_POINT_DECIMALS)
    len= my_gcvt(nr, MY_GCVT_ARG_DOUBLE, to_length - 1, to, NULL);
  else
    len= my_fcvt(nr, dec, to, NULL);

  val_buffer->length((uint) len);
  if (zerofill)
    prepend_zeros(val_buffer);
  val_buffer->set_charset(&my_charset_numeric);
  return val_buffer;
}

bool Field_double::send(Protocol *protocol)
{
  DBUG_ASSERT(marked_for_read());
  Protocol_text *txt;
  if (unlikely(zerofill) && (txt= dynamic_cast<Protocol_text*>(protocol)))
    return send_numeric_zerofill_str(txt, PROTOCOL_SEND_DOUBLE);
  return protocol->store_double(Field_double::val_real(), dec);
}


int Field_double::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  double a,b;
  float8get(a,a_ptr);
  float8get(b,b_ptr);
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}


#define DBL_EXP_DIG (sizeof(double)*8-DBL_MANT_DIG)

/* The following should work for IEEE */

void Field_double::sort_string(uchar *to,uint length __attribute__((unused)))
{
  double nr;
  float8get(nr,ptr);
  change_double_for_sort(nr, to);
}


/**
   Save the field metadata for double fields.

   Saves the pack length in the first byte of the field metadata array
   at index of *metadata_ptr.

   @param   metadata_ptr   First byte of field metadata

   @returns number of bytes written to metadata_ptr
*/
Binlog_type_info Field_double::binlog_type_info() const
{
  DBUG_ASSERT(Field_double::type() == binlog_type());
  return Binlog_type_info(Field_double::type(), pack_length(), 1,
                          binlog_signedness());
}


/**
  TIMESTAMP type holds datetime values in range from 1970-01-01 00:00:01 UTC to 
  2038-01-01 00:00:00 UTC stored as number of seconds since Unix 
  Epoch in UTC.
  
  Actually SQL-99 says that we should allow niladic functions (like NOW())
  as defaults for any field. The current limitation (only NOW() and only 
  for TIMESTAMP and DATETIME fields) are because of restricted binary .frm
  format and should go away in the future.
  
  Also because of this limitation of binary .frm format we use 5 different
  unireg_check values with TIMESTAMP field to distinguish various cases of
  DEFAULT or ON UPDATE values. These values are:
  
  TIMESTAMP_OLD_FIELD - old timestamp, if there was not any fields with
    auto-set-on-update (or now() as default) in this table before, then this 
    field has NOW() as default and is updated when row changes, else it is 
    field which has 0 as default value and is not automatically updated.
  TIMESTAMP_DN_FIELD - field with NOW() as default but not set on update
    automatically (TIMESTAMP DEFAULT NOW()), not used in Field since 10.2.2
  TIMESTAMP_UN_FIELD - field which is set on update automatically but has not 
    NOW() as default (but it may has 0 or some other const timestamp as 
    default) (TIMESTAMP ON UPDATE NOW()).
  TIMESTAMP_DNUN_FIELD - field which has now() as default and is auto-set on 
    update. (TIMESTAMP DEFAULT NOW() ON UPDATE NOW()), not used in Field since 10.2.2
  NONE - field which is not auto-set on update with some other than NOW() 
    default value (TIMESTAMP DEFAULT 0).

  Note that TIMESTAMP_OLD_FIELDs are never created explicitly now, they are 
  left only for preserving ability to read old tables. Such fields replaced 
  with their newer analogs in CREATE TABLE and in SHOW CREATE TABLE. This is 
  because we want to prefer NONE unireg_check before TIMESTAMP_OLD_FIELD for 
  "TIMESTAMP DEFAULT 'Const'" field. (Old timestamps allowed such 
  specification too but ignored default value for first timestamp, which of 
  course is non-standard.) In most cases user won't notice any change, only
  exception is different behavior of old/new timestamps during ALTER TABLE.
 */

Field_timestamp::Field_timestamp(uchar *ptr_arg, uint32 len_arg,
                                 uchar *null_ptr_arg, uchar null_bit_arg,
				 enum utype unireg_check_arg,
				 const LEX_CSTRING *field_name_arg,
				 TABLE_SHARE *share)
  :Field_temporal(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
                  unireg_check_arg, field_name_arg)
{
  /* For 4.0 MYD and 4.0 InnoDB compatibility */
  flags|= UNSIGNED_FLAG;
  if (unireg_check != NONE)
  {
    /*
      We mark the flag with TIMESTAMP_FLAG to indicate to the client that
      this field will be automatically updated on insert.
    */
    flags|= TIMESTAMP_FLAG;
    if (unireg_check != TIMESTAMP_DN_FIELD)
      flags|= ON_UPDATE_NOW_FLAG;
  }
}


sql_mode_t
Field_timestamp::conversion_depends_on_sql_mode(THD *thd, Item *expr) const
{
  return expr->datetime_precision(thd) > decimals() ?
         MODE_TIME_ROUND_FRACTIONAL : 0;
}


int Field_timestamp::save_in_field(Field *to)
{
  ulong sec_part;
  my_time_t ts= get_timestamp(&sec_part);
  return to->store_timestamp_dec(Timeval(ts, sec_part), decimals());
}

my_time_t Field_timestamp0::get_timestamp(const uchar *pos,
                                          ulong *sec_part) const
{
  DBUG_ASSERT(marked_for_read());
  *sec_part= 0;
  return sint4korr(pos);
}


bool Field_timestamp0::val_native(Native *to)
{
  DBUG_ASSERT(marked_for_read());
  my_time_t sec= (my_time_t) sint4korr(ptr);
  return Timestamp_or_zero_datetime(Timestamp(sec, 0), sec == 0).
           to_native(to, 0);
}


int Field_timestamp::store_TIME_with_warning(THD *thd, const Datetime *dt,
                                             const ErrConv *str, int was_cut)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  static const Timestamp zero(0, 0);

  // Handle totally bad values
  if (!dt->is_valid_datetime())
  {
    set_datetime_warning(WARN_DATA_TRUNCATED, str, "datetime", 1);
    store_TIMESTAMP(zero);
    return 1;
  }

  // Handle values that do not need DATETIME to TIMESTAMP conversion
  if (!dt->get_mysql_time()->month)
  {
    /*
      Zero date is allowed by the current sql_mode. Store zero timestamp.
      Return success or a warning about non-fatal truncation, e.g.:
        INSERT INTO t1 (ts) VALUES ('0000-00-00 00:00:00 some tail');
    */
    store_TIMESTAMP(zero);
    return store_TIME_return_code_with_warnings(was_cut, str, "datetime");
  }

  // Convert DATETIME to TIMESTAMP
  uint conversion_error;
  const MYSQL_TIME *l_time= dt->get_mysql_time();
  my_time_t timestamp= TIME_to_timestamp(thd, l_time, &conversion_error);
  if (timestamp == 0 && l_time->second_part == 0)
  {
    set_datetime_warning(ER_WARN_DATA_OUT_OF_RANGE, str, "datetime", 1);
    store_TIMESTAMP(zero);
    return 1; // date was fine but pointed to a DST gap
  }

  // Store the value
  DBUG_ASSERT(!dt->fraction_remainder(decimals()));
  store_TIMESTAMP(Timestamp(timestamp, l_time->second_part));

  // Calculate return value and send warnings if needed
  if (unlikely(conversion_error)) // e.g. DATETIME in the DST gap
  {
    set_datetime_warning(conversion_error, str, "datetime", 1);
    return 1;
  }
  return store_TIME_return_code_with_warnings(was_cut, str, "datetime");
}


date_conv_mode_t Timestamp::sql_mode_for_timestamp(THD *thd)
{
  // We don't want to store invalid or fuzzy datetime values in TIMESTAMP
  return date_conv_mode_t((thd->variables.sql_mode & MODE_NO_ZERO_DATE) |
                          MODE_NO_ZERO_IN_DATE);
}


int Field_timestamp::store_time_dec(const MYSQL_TIME *ltime, uint dec)
{
  int warn;
  ErrConvTime str(ltime);
  THD *thd= get_thd();
  Datetime dt(thd, &warn, ltime, Timestamp::DatetimeOptions(thd), decimals());
  return store_TIME_with_warning(thd, &dt, &str, warn);
}


int Field_timestamp::store(const char *from,size_t len,CHARSET_INFO *cs)
{
  ErrConvString str(from, len, cs);
  THD *thd= get_thd();
  MYSQL_TIME_STATUS st;
  Datetime dt(thd, &st, from, len, cs, Timestamp::DatetimeOptions(thd), decimals());
  return store_TIME_with_warning(thd, &dt, &str, st.warnings);
}


int Field_timestamp::store(double nr)
{
  int error;
  ErrConvDouble str(nr);
  THD *thd= get_thd();
  Datetime dt(thd, &error, nr, Timestamp::DatetimeOptions(thd), decimals());
  return store_TIME_with_warning(thd, &dt, &str, error);
}


int Field_timestamp::store(longlong nr, bool unsigned_val)
{
  int error;
  Longlong_hybrid tmp(nr, unsigned_val);
  ErrConvInteger str(tmp);
  THD *thd= get_thd();
  Datetime dt(&error, tmp, Timestamp::DatetimeOptions(thd));
  return store_TIME_with_warning(thd, &dt, &str, error);
}


int Field_timestamp::store_timestamp_dec(const timeval &ts, uint dec)
{
  int warn= 0;
  time_round_mode_t mode= Datetime::default_round_mode(get_thd());
  store_TIMESTAMP(Timestamp(ts).round(decimals(), mode, &warn));
  if (warn)
  {
    /*
      We're here if rounding would overflow outside of the supported TIMESTAMP
      range, so truncation happened instead:
        CREATE TABLE t1 (a TIMESTAMP(6));
        INSERT INTO t1 VALUES ('maximum-possible-timestamp.999999');
        ALTER TABLE t1 MODIFY a TIMESTAMP(5);
        SELECT * FROM t1; --> 'maximum-possible-timestamp.99999' (5 digits)
      Raise a warning, like DATETIME does for '9999-12-31 23:59:59.999999'.
    */
    set_warning(Sql_condition::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
  }
  if (ts.tv_sec == 0 && ts.tv_usec == 0 &&
      get_thd()->variables.sql_mode & (ulonglong) TIME_NO_ZERO_DATE)
    return zero_time_stored_return_code_with_warning();
  return 0;
}


int Field_timestamp::zero_time_stored_return_code_with_warning()
{
  if (get_thd()->variables.sql_mode & (ulonglong) TIME_NO_ZERO_DATE)
  {
    ErrConvString s(
      STRING_WITH_LEN("0000-00-00 00:00:00.000000") - (decimals() ? 6 - decimals() : 7),
      system_charset_info);
    set_datetime_warning(WARN_DATA_TRUNCATED, &s, "datetime", 1);
    return 1;
  }
  return 0;

}


int Field_timestamp::store_native(const Native &value)
{
  if (!value.length()) // Zero datetime
  {
    reset();
    return zero_time_stored_return_code_with_warning();
  }
  /*
    The exact second precision is not important here.
    Field_timestamp*::store_timestamp_dec() do not use the "dec" parameter.
    Passing TIME_SECOND_PART_DIGITS is OK.
  */
  return store_timestamp_dec(Timestamp(value).tv(), TIME_SECOND_PART_DIGITS);
}


longlong Field_timestamp::val_int(void)
{
  MYSQL_TIME ltime;
  if (get_date(&ltime, Datetime::Options(TIME_NO_ZERO_DATE, get_thd())))
    return 0;

  return ltime.year * 10000000000LL + ltime.month * 100000000LL +
         ltime.day * 1000000L + ltime.hour * 10000L +
         ltime.minute * 100 + ltime.second;
}


String *Field_timestamp::val_str(String *val_buffer, String *val_ptr)
{
  MYSQL_TIME ltime;
  uint32 temp, temp2;
  uint dec;
  char *to;

  val_buffer->alloc(field_length+1);
  to= (char*) val_buffer->ptr();
  val_buffer->length(field_length);

  if (get_date(&ltime, Datetime::Options(TIME_NO_ZERO_DATE, get_thd())))
  {				      /* Zero time is "000000" */
    val_ptr->set(zero_timestamp, field_length, &my_charset_numeric);
    return val_ptr;
  }
  val_buffer->set_charset(&my_charset_numeric);	// Safety
   
  temp= ltime.year % 100;
  if (temp < YY_PART_YEAR - 1)
  {
    *to++= '2';
    *to++= '0';
  }
  else
  {
    *to++= '1';
    *to++= '9';
  }
  temp2=temp/10; temp=temp-temp2*10;
  *to++= (char) ('0'+(char) (temp2));
  *to++= (char) ('0'+(char) (temp));
  *to++= '-';
  temp=ltime.month;
  temp2=temp/10; temp=temp-temp2*10;
  *to++= (char) ('0'+(char) (temp2));
  *to++= (char) ('0'+(char) (temp));
  *to++= '-';
  temp=ltime.day;
  temp2=temp/10; temp=temp-temp2*10;
  *to++= (char) ('0'+(char) (temp2));
  *to++= (char) ('0'+(char) (temp));
  *to++= ' ';
  temp=ltime.hour;
  temp2=temp/10; temp=temp-temp2*10;
  *to++= (char) ('0'+(char) (temp2));
  *to++= (char) ('0'+(char) (temp));
  *to++= ':';
  temp=ltime.minute;
  temp2=temp/10; temp=temp-temp2*10;
  *to++= (char) ('0'+(char) (temp2));
  *to++= (char) ('0'+(char) (temp));
  *to++= ':';
  temp=ltime.second;
  temp2=temp/10; temp=temp-temp2*10;
  *to++= (char) ('0'+(char) (temp2));
  *to++= (char) ('0'+(char) (temp));
  *to= 0;
  val_buffer->set_charset(&my_charset_numeric);

  if ((dec= decimals()))
  {
    ulong sec_part= (ulong) sec_part_shift(ltime.second_part, dec);
    char *buf= const_cast<char*>(val_buffer->ptr() + MAX_DATETIME_WIDTH);
    for (int i= dec; i > 0; i--, sec_part/= 10)
    buf[i]= (char)(sec_part % 10) + '0';
    buf[0]= '.';
    buf[dec + 1]= 0;
  }
  return val_buffer;
}


bool
Field_timestamp::validate_value_in_record(THD *thd, const uchar *record) const
{
  DBUG_ASSERT(!is_null_in_record(record));
  ulong sec_part;
  return !get_timestamp(ptr_in_record(record), &sec_part) && !sec_part &&
         bool(sql_mode_for_dates(thd) & TIME_NO_ZERO_DATE) != false;
}


bool Field_timestamp::get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate)
{
  ulong sec_part;
  my_time_t ts= get_timestamp(&sec_part);
  return get_thd()->timestamp_to_TIME(ltime, ts, sec_part, fuzzydate);
}


bool Field_timestamp0::send(Protocol *protocol)
{
  MYSQL_TIME ltime;
  Field_timestamp0::get_date(&ltime, date_mode_t(0));
  return protocol->store_datetime(&ltime, 0);
}


int Field_timestamp0::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  int32 a,b;
  a=sint4korr(a_ptr);
  b=sint4korr(b_ptr);
  return ((uint32) a < (uint32) b) ? -1 : ((uint32) a > (uint32) b) ? 1 : 0;
}


void Field_timestamp0::sort_string(uchar *to,uint length __attribute__((unused)))
{
  to[0] = ptr[3];
  to[1] = ptr[2];
  to[2] = ptr[1];
  to[3] = ptr[0];
}


int Field_timestamp0::set_time()
{
  set_notnull();
  store_TIMESTAMP(Timestamp(get_thd()->query_start(), 0));
  return 0;
}


bool Field_timestamp::load_data_set_no_data(THD *thd, bool fixed_format)
{
  if (!maybe_null())
  {
    /*
      Timestamp fields that are NOT NULL are autoupdated if there is no
      corresponding value in the data file.
    */
    set_time();
    set_has_explicit_value();
    return false;
  }
  return Field::load_data_set_no_data(thd, fixed_format);
}


bool Field_timestamp::load_data_set_null(THD *thd)
{
  if (!maybe_null())
  {
    /*
      Timestamp fields that are NOT NULL are autoupdated if there is no
      corresponding value in the data file.
    */
    set_time();
  }
  else
  {
    reset();
    set_null();
  }
  set_has_explicit_value(); // Do not auto-update this field
  return false;
}


#ifdef NOT_USED
static void store_native(ulonglong num, uchar *to, uint bytes)
{
  switch(bytes) {
  case 1: *to= (uchar)num;              break;
  case 2: shortstore(to, (ushort)num);  break;
  case 3: int3store(to, num); /* Sic!*/ break;
  case 4: longstore(to, (ulong)num);    break;
  case 8: longlongstore(to, num);       break;
  default: DBUG_ASSERT(0);
  }
}

static longlong read_native(const uchar *from, uint bytes)
{
  switch(bytes) {
  case 1: return from[0];
  case 2: { uint16 tmp; shortget(tmp, from); return tmp; }
  case 3: return uint3korr(from);
  case 4: { uint32 tmp; longget(tmp, from); return tmp; }
  case 8: { longlong tmp; longlongget(tmp, from); return tmp; }
  default: DBUG_ASSERT(0); return 0;
  }
}
#endif


void Field_timestamp_hires::store_TIMEVAL(const timeval &tv)
{
  mi_int4store(ptr, tv.tv_sec);
  store_bigendian(sec_part_shift(tv.tv_usec, dec), ptr+4, sec_part_bytes(dec));
}

my_time_t Field_timestamp_hires::get_timestamp(const uchar *pos,
                                               ulong *sec_part) const
{
  DBUG_ASSERT(marked_for_read());
  *sec_part= (long)sec_part_unshift(read_bigendian(pos+4, sec_part_bytes(dec)), dec);
  return mi_uint4korr(pos);
}


bool Field_timestamp_hires::val_native(Native *to)
{
  DBUG_ASSERT(marked_for_read());
  struct timeval tm;
  tm.tv_sec= mi_uint4korr(ptr);
  tm.tv_usec= (ulong) sec_part_unshift(read_bigendian(ptr+4, sec_part_bytes(dec)), dec);
  return Timestamp_or_zero_datetime(Timestamp(tm), tm.tv_sec == 0).
           to_native(to, dec);
}


double Field_timestamp_with_dec::val_real(void)
{
  MYSQL_TIME ltime;
  if (get_date(&ltime, Datetime::Options(TIME_NO_ZERO_DATE, get_thd())))
    return 0;
  
  return ltime.year * 1e10 + ltime.month * 1e8 +
         ltime.day * 1e6 + ltime.hour * 1e4 +
         ltime.minute * 1e2 + ltime.second + ltime.second_part*1e-6;
}

my_decimal *Field_timestamp_with_dec::val_decimal(my_decimal *d)
{
  MYSQL_TIME ltime;
  get_date(&ltime, date_mode_t(0));
  return TIME_to_my_decimal(&ltime, d);
}
 
int Field_timestamp::store_decimal(const my_decimal *d)
{
  int error;
  THD *thd= get_thd();
  ErrConvDecimal str(d);
  Datetime dt(thd, &error, d, Timestamp::DatetimeOptions(thd), decimals());
  return store_TIME_with_warning(thd, &dt, &str, error);
}

int Field_timestamp_with_dec::set_time()
{
  THD *thd= get_thd();
  set_notnull();
  // Avoid writing microseconds into binlog for FSP=0
  ulong msec= decimals() ? thd->query_start_sec_part() : 0;
  store_TIMESTAMP(Timestamp(thd->query_start(), msec).trunc(decimals()));
  return 0;
}

bool Field_timestamp_with_dec::send(Protocol *protocol)
{
  MYSQL_TIME ltime;
  Field_timestamp::get_date(&ltime, date_mode_t(0));
  return protocol->store_datetime(&ltime, dec);
}


int Field_timestamp_hires::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  int32 a,b;
  ulong a_sec_part, b_sec_part;
  a= mi_uint4korr(a_ptr);
  a_sec_part= (ulong)read_bigendian(a_ptr+4, sec_part_bytes(dec));
  b= mi_uint4korr(b_ptr);
  b_sec_part= (ulong)read_bigendian(b_ptr+4, sec_part_bytes(dec));
  return ((uint32) a < (uint32) b) ? -1 : ((uint32) a > (uint32) b) ? 1 :
          a_sec_part < b_sec_part  ? -1 :  a_sec_part > b_sec_part  ? 1 : 0;
}


void Field_timestamp_with_dec::make_send_field(Send_field *field)
{
  Field::make_send_field(field);
  field->decimals= dec;
}


/*************************************************************
** MySQL-5.6 compatible TIMESTAMP(N)
**************************************************************/

void Field_timestampf::store_TIMEVAL(const timeval &tm)
{
  my_timestamp_to_binary(&tm, ptr, dec);
}

void Field_timestampf::set_max()
{
  DBUG_ENTER("Field_timestampf::set_max");
  DBUG_ASSERT(marked_for_write_or_computed());
  DBUG_ASSERT(dec == TIME_SECOND_PART_DIGITS);

  set_notnull();
  mi_int4store(ptr, TIMESTAMP_MAX_VALUE);
  mi_int3store(ptr + 4, TIME_MAX_SECOND_PART);

  DBUG_VOID_RETURN;
}

bool Field_timestampf::is_max()
{
  DBUG_ENTER("Field_timestampf::is_max");
  DBUG_ASSERT(marked_for_read());

  DBUG_RETURN(mi_sint4korr(ptr) == TIMESTAMP_MAX_VALUE &&
              mi_sint3korr(ptr + 4) == TIME_MAX_SECOND_PART);
}

my_time_t Field_timestampf::get_timestamp(const uchar *pos,
                                          ulong *sec_part) const
{
  struct timeval tm;
  my_timestamp_from_binary(&tm, pos, dec);
  *sec_part= tm.tv_usec;
  return tm.tv_sec;
}


bool Field_timestampf::val_native(Native *to)
{
  DBUG_ASSERT(marked_for_read());
  // Check if it's '0000-00-00 00:00:00' rather than a real timestamp
  if (ptr[0] == 0 && ptr[1] == 0 && ptr[2] == 0 && ptr[3] == 0)
  {
    to->length(0);
    return false;
  }
  return Field::val_native(to);
}

Binlog_type_info Field_timestampf::binlog_type_info() const
{
  return Binlog_type_info(Field_timestampf::binlog_type(), decimals(), 1);
}


/*************************************************************/
sql_mode_t Field_temporal::can_handle_sql_mode_dependency_on_store() const
{
  return MODE_PAD_CHAR_TO_FULL_LENGTH;
}


bool Field_temporal::is_equal(const Column_definition &new_field) const
{
  return new_field.type_handler() == type_handler() &&
         new_field.length == max_display_length();
}


void Field_temporal::set_warnings(Sql_condition::enum_warning_level trunc_level,
                                  const ErrConv *str, int was_cut,
                                  const char *typestr)
{
  /*
    error code logic:
    MYSQL_TIME_WARN_TRUNCATED means that the value was not a date/time at all.
      it will be stored as zero date/time.
    MYSQL_TIME_WARN_OUT_OF_RANGE means that the value was a date/time,
      that is, it was parsed as such, but the value was invalid.

    Also, MYSQL_TIME_WARN_TRUNCATED is used when storing a DATETIME in
    a DATE field and non-zero time part is thrown away.
  */
  if (was_cut & MYSQL_TIME_WARN_TRUNCATED)
    set_datetime_warning(trunc_level, WARN_DATA_TRUNCATED, str, typestr, 1);
  if (was_cut & MYSQL_TIME_WARN_OUT_OF_RANGE)
    set_datetime_warning(ER_WARN_DATA_OUT_OF_RANGE, str, typestr, 1);
}


void Field_temporal::sql_type_dec_comment(String &res,
                                          const Name &name,
                                          uint dec,
                                          const Name &comment) const
{
  CHARSET_INFO *cs=res.charset();
  res.length(cs->cset->snprintf(cs, (char*) res.ptr(), res.alloced_length(),
                                "%.*s(%u)%s%.*s%s",
                                (uint) name.length(), name.ptr(),
                                dec,
                                comment.length() ? " /* " : "",
                                (uint) comment.length(), comment.ptr(),
                                comment.length() ? " */" : ""));
}


void Field_temporal::sql_type_comment(String &res,
                                      const Name &name,
                                      const Name &comment) const
{
  CHARSET_INFO *cs=res.charset();
  res.length(cs->cset->snprintf(cs, (char*) res.ptr(), res.alloced_length(),
                                "%.*s%s%.*s%s",
                                (uint) name.length(), name.ptr(),
                                comment.length() ? " /* " : "",
                                (uint) comment.length(), comment.ptr(),
                                comment.length() ? " */" : ""));
}


const Name & Field_temporal::type_version_mysql56()
{
  DBUG_EXECUTE_IF("sql_type", return Type_handler::version_mysql56(); );
  static Name none(NULL, 0);
  return none;
}


/*
  Store string into a date/time field

  RETURN
    0  ok
    1  Value was cut during conversion
    2  value was out of range
    3  Datetime value that was cut (warning level NOTE)
       This is used by opt_range.cc:get_mm_leaf().
*/
int Field_datetime::store_TIME_with_warning(const Datetime *dt,
                                            const ErrConv *str,
                                            int was_cut)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  // Handle totally bad values
  if (!dt->is_valid_datetime())
    return store_invalid_with_warning(str, was_cut, "datetime");
  // Store the value
  DBUG_ASSERT(!dt->fraction_remainder(decimals()));
  store_datetime(*dt);
  // Caclulate return value and send warnings if needed
  return store_TIME_return_code_with_warnings(was_cut, str, "datetime");
}


int Field_datetime::store(const char *from, size_t len, CHARSET_INFO *cs)
{
  MYSQL_TIME_STATUS st;
  ErrConvString str(from, len, cs);
  THD *thd= get_thd();
  Datetime dt(thd, &st, from, len, cs, Datetime::Options(thd), decimals());
  return store_TIME_with_warning(&dt, &str, st.warnings);
}

int Field_datetime::store(double nr)
{
  int error;
  ErrConvDouble str(nr);
  THD *thd= get_thd();
  Datetime dt(thd, &error, nr, Datetime::Options(thd), decimals());
  return store_TIME_with_warning(&dt, &str, error);
}


int Field_datetime::store(longlong nr, bool unsigned_val)
{
  int error;
  Longlong_hybrid tmp(nr, unsigned_val);
  ErrConvInteger str(tmp);
  THD *thd= get_thd();
  Datetime dt(&error, tmp, Datetime::Options(thd));
  return store_TIME_with_warning(&dt, &str, error);
}

int Field_datetime::store_time_dec(const MYSQL_TIME *ltime, uint dec)
{
  int error;
  ErrConvTime str(ltime);
  THD *thd= get_thd();
  Datetime dt(thd, &error, ltime, Datetime::Options(thd), decimals());
  return store_TIME_with_warning(&dt, &str, error);
}


int Field_datetime::store_decimal(const my_decimal *d)
{
  int error;
  ErrConvDecimal str(d);
  THD *thd= get_thd();
  Datetime tm(thd, &error, d, Datetime::Options(thd), decimals());
  return store_TIME_with_warning(&tm, &str, error);
}


bool
Field_temporal_with_date::validate_value_in_record(THD *thd,
                                                   const uchar *record) const
{
  DBUG_ASSERT(!is_null_in_record(record));
  MYSQL_TIME ltime;
  return get_TIME(&ltime, ptr_in_record(record), Datetime::Options(thd));
}


my_decimal *Field_temporal::val_decimal(my_decimal *d)
{
  MYSQL_TIME ltime;
  if (get_date(&ltime, date_mode_t(0)))
  {
    bzero(&ltime, sizeof(ltime));
    ltime.time_type= type_handler()->mysql_timestamp_type();
  }
  return TIME_to_my_decimal(&ltime, d);
}


bool Field_temporal::can_optimize_keypart_ref(const Item_bool_func *cond,
                                              const Item *value) const
{
  return true; // Field is of TIME_RESULT, which supersedes everything else.
}


bool Field_temporal::can_optimize_group_min_max(const Item_bool_func *cond,
                                                const Item *const_item) const
{
  return true; // Field is of TIME_RESULT, which supersedes everything else.
}


Item *Field_temporal::get_equal_const_item_datetime(THD *thd,
                                                    const Context &ctx,
                                                    Item *const_item)
{
  switch (ctx.subst_constraint()) {
  case IDENTITY_SUBST:
    if ((const_item->field_type() != MYSQL_TYPE_DATETIME &&
         const_item->field_type() != MYSQL_TYPE_TIMESTAMP) ||
        const_item->decimals != decimals())
    {
      Datetime::Options opt(TIME_CONV_NONE, thd);
      Datetime dt(thd, const_item, opt, decimals());
      if (!dt.is_valid_datetime())
        return NULL;
      /*
        See comments about truncation in the same place in
        Field_time::get_equal_const_item().
      */
      return new (thd->mem_root) Item_datetime_literal(thd, &dt, decimals());
    }
    break;
  case ANY_SUBST:
    if (!is_temporal_type_with_date(const_item->field_type()))
    {
      Datetime dt= type_handler()->field_type() == MYSQL_TYPE_TIMESTAMP ?
        Datetime(thd, const_item, Timestamp::DatetimeOptions(thd)) :
        Datetime(thd, const_item, Datetime::Options_cmp(thd));
      if (!dt.is_valid_datetime())
        return NULL;
      return new (thd->mem_root)
        Item_datetime_literal_for_invalid_dates(thd, &dt,
                                                dt.get_mysql_time()->
                                                second_part ?
                                                TIME_SECOND_PART_DIGITS : 0);
    }
    break;
  }
  return const_item;
}


/****************************************************************************
** time type
** In string context: HH:MM:SS
** In number context: HHMMSS
** Stored as a 3 byte unsigned int
****************************************************************************/
sql_mode_t
Field_time::conversion_depends_on_sql_mode(THD *thd, Item *expr) const
{
  return expr->time_precision(thd) > decimals() ?
         MODE_TIME_ROUND_FRACTIONAL : 0;
}


int Field_time::store_TIME_with_warning(const Time *t,
                                        const ErrConv *str, int warn)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  // Handle totally bad values
  if (!t->is_valid_time())
    return store_invalid_with_warning(str, warn, "time");
  // Store the value
  DBUG_ASSERT(!t->fraction_remainder(decimals()));
  store_TIME(*t);
  // Calculate return value and send warnings if needed
  return store_TIME_return_code_with_warnings(warn, str, "time");
}


void Field_time0::store_TIME(const MYSQL_TIME *ltime)
{
  DBUG_ASSERT(ltime->year == 0);
  DBUG_ASSERT(ltime->month == 0);
  long tmp= (ltime->day*24L+ltime->hour)*10000L +
            (ltime->minute*100+ltime->second);
  if (ltime->neg)
    tmp= -tmp;
  int3store(ptr,tmp);
}

int Field_time::store(const char *from,size_t len,CHARSET_INFO *cs)
{
  ErrConvString str(from, len, cs);
  MYSQL_TIME_STATUS st;
  THD *thd= get_thd();
  /*
    Unlike number-to-time conversion, we need to additionally pass
    MODE_NO_ZERO_DATE here (if it presents in the current sql_mode):
      SET sql_mode='STRICT_ALL_TABLES,NO_ZERO_DATE';
      INSERT INTO t1 VALUES ('0000-00-00 00:00:00');  -- error
      INSERT INTO t1 VALUES (0);                      -- ok
    In the first INSERT we have a zero date.
    In the second INSERT we don't have a zero date (it is just a zero time).
  */
  Time::Options opt(sql_mode_for_dates(thd), thd);
  Time tm(thd, &st, from, len, cs, opt, decimals());
  return store_TIME_with_warning(&tm, &str, st.warnings);
}


int Field_time::store_time_dec(const MYSQL_TIME *ltime, uint dec)
{
  ErrConvTime str(ltime);
  int warn;
  Time tm(&warn, ltime, curdays, Time::Options(get_thd()), decimals());
  return store_TIME_with_warning(&tm, &str, warn);
}


int Field_time::store(double nr)
{
  ErrConvDouble str(nr);
  int was_cut;
  Time tm(get_thd(), &was_cut, nr, Time::Options(get_thd()), decimals());
  return store_TIME_with_warning(&tm, &str, was_cut);
}


int Field_time::store(longlong nr, bool unsigned_val)
{
  Longlong_hybrid tmp(nr, unsigned_val);
  ErrConvInteger str(tmp);
  int was_cut;
  THD *thd= get_thd();
  /*
    Need fractional digit truncation if nr overflows to '838:59:59.999999'.
    The constructor used below will always truncate (never round).
    We don't need to care to overwrite the default session rounding mode
    from HALF_UP to TRUNCATE.
  */
  Time tm(thd, &was_cut, tmp, Time::Options(thd), decimals());
  return store_TIME_with_warning(&tm, &str, was_cut);
}


void Field_time::set_curdays(THD *thd)
{
  MYSQL_TIME ltime;
  set_current_date(thd, &ltime);
  curdays= calc_daynr(ltime.year, ltime.month, ltime.day);
}


Field *Field_time::new_key_field(MEM_ROOT *root, TABLE *new_table,
                                 uchar *new_ptr, uint32 length,
                                 uchar *new_null_ptr, uint new_null_bit)
{
  THD *thd= get_thd();
  Field_time *res=
    (Field_time*) Field::new_key_field(root, new_table, new_ptr, length,
                                       new_null_ptr, new_null_bit);
  if (!(thd->variables.old_behavior & OLD_MODE_ZERO_DATE_TIME_CAST) && res)
    res->set_curdays(thd);
  return res;
}


double Field_time0::val_real(void)
{
  DBUG_ASSERT(marked_for_read());
  uint32 j= (uint32) uint3korr(ptr);
  return (double) j;
}

longlong Field_time0::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  return (longlong) sint3korr(ptr);
}


/**
  @note
  This function is multi-byte safe as the result string is always of type
  my_charset_bin
*/

String *Field_time::val_str(String *str,
			    String *unused __attribute__((unused)))
{
  DBUG_ASSERT(marked_for_read());
  MYSQL_TIME ltime;
  get_date(&ltime, Datetime::Options(TIME_TIME_ONLY, get_thd()));
  str->alloc(field_length + 1);
  str->length(my_time_to_str(&ltime, const_cast<char*>(str->ptr()), decimals()));
  str->set_charset(&my_charset_numeric);
  return str;
}


bool Field_time::check_zero_in_date_with_warn(date_mode_t fuzzydate)
{
  date_conv_mode_t tmp= date_conv_mode_t(fuzzydate);
  if (!(tmp & TIME_TIME_ONLY) && (tmp & TIME_NO_ZERO_IN_DATE))
  {
    THD *thd= get_thd();
    push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
                        ER_WARN_DATA_OUT_OF_RANGE,
                        ER_THD(thd, ER_WARN_DATA_OUT_OF_RANGE), field_name.str,
                        thd->get_stmt_da()->current_row_for_warning());
    return true;
  }
  return false;
}


/**
  @note
  Normally we would not consider 'time' as a valid date, but we allow
  get_date() here to be able to do things like
  DATE_FORMAT(time, "%l.%i %p")
*/
 
bool Field_time0::get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate)
{
  if (check_zero_in_date_with_warn(fuzzydate))
    return true;
  long tmp=(long) sint3korr(ptr);
  ltime->neg=0;
  if (tmp < 0)
  {
    ltime->neg= 1;
    tmp=-tmp;
  }
  ltime->year= ltime->month= ltime->day= 0;
  ltime->hour=   (int) (tmp/10000);
  tmp-=ltime->hour*10000;
  ltime->minute= (int) tmp/100;
  ltime->second= (int) tmp % 100;
  ltime->second_part=0;
  ltime->time_type= MYSQL_TIMESTAMP_TIME;
  return 0;
}


int Field_time::store_native(const Native &value)
{
  Time t(value);
  DBUG_ASSERT(t.is_valid_time());
  store_TIME(t);
  return 0;
}


bool Field_time::val_native(Native *to)
{
  MYSQL_TIME ltime;
  get_date(&ltime, date_mode_t(0));
  int warn;
  return Time(&warn, &ltime, 0).to_native(to, decimals());
}


bool Field_time::send(Protocol *protocol)
{
  MYSQL_TIME ltime;
  get_date(&ltime, Time::Options(TIME_TIME_ONLY, get_thd()));
  return protocol->store_time(&ltime, decimals());
}


int Field_time0::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  int32 a,b;
  a=(int32) sint3korr(a_ptr);
  b=(int32) sint3korr(b_ptr);
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

void Field_time0::sort_string(uchar *to,uint length __attribute__((unused)))
{
  to[0] = (uchar) (ptr[2] ^ 128);
  to[1] = ptr[1];
  to[2] = ptr[0];
}


int Field_time_hires::reset()
{
  store_bigendian(zero_point, ptr, Field_time_hires::pack_length());
  return 0;
}


void Field_time_hires::store_TIME(const MYSQL_TIME *ltime)
{
  DBUG_ASSERT(ltime->year == 0);
  DBUG_ASSERT(ltime->month == 0);
  ulonglong packed= sec_part_shift(pack_time(ltime), dec) + zero_point;
  store_bigendian(packed, ptr, Field_time_hires::pack_length());
}

int Field_time::store_decimal(const my_decimal *d)
{
  ErrConvDecimal str(d);
  int was_cut;
  Time tm(get_thd(), &was_cut, d, Time::Options(get_thd()), decimals());
  return store_TIME_with_warning(&tm, &str, was_cut);
}


bool Field_time::can_be_substituted_to_equal_item(const Context &ctx,
                                                  const Item_equal *item_equal)
{
  DBUG_ASSERT(item_equal->compare_type_handler()->cmp_type() != STRING_RESULT);
  switch (ctx.subst_constraint()) {
  case ANY_SUBST:
    /*
      A TIME field in a DATETIME comparison can be substituted to
      Item_equal with TIME comparison.

        SET timestamp=UNIX_TIMESTAMP('2015-08-30 10:20:30');
        CREATE OR REPLACE TABLE t1 (a TIME);
        INSERT INTO t1 VALUES ('00:00:00'),('00:00:01');
        SELECT * FROM t1 WHERE a>=TIMESTAMP'2015-08-30 00:00:00'
                         AND a='00:00:00';

      The above query can be simplified to:
        SELECT * FROM t1 WHERE TIME'00:00:00'>=TIMESTAMP'2015-08-30 00:00:00'
                           AND a='00:00:00';
      And further to:
        SELECT * FROM t1 WHERE a=TIME'00:00:00';
    */
    if (ctx.compare_type_handler() == &type_handler_datetime &&
        item_equal->compare_type_handler() == &type_handler_time)
      return true;
    return ctx.compare_type_handler() == item_equal->compare_type_handler();
  case IDENTITY_SUBST:
    return true;
  }
  return false;
}


Item *Field_time::get_equal_const_item(THD *thd, const Context &ctx,
                                       Item *const_item)
{
  /*
    Old mode conversion from DATETIME with non-zero YYYYMMDD part
    to TIME works very inconsistently. Possible variants:
    - truncate the YYYYMMDD part
    - add (MM*33+DD)*24 to hours
    - add (MM*31+DD)*24 to hours
    Let's disallow propagation of DATETIME with non-zero YYYYMMDD
    as an equal constant for a TIME field.
  */
  Time::datetime_to_time_mode_t mode=
    (thd->variables.old_behavior & OLD_MODE_ZERO_DATE_TIME_CAST) ?
    Time::DATETIME_TO_TIME_YYYYMMDD_00000000_ONLY :
    Time::DATETIME_TO_TIME_MINUS_CURRENT_DATE;

  switch (ctx.subst_constraint()) {
  case ANY_SUBST:
    if (const_item->field_type() != MYSQL_TYPE_TIME)
    {
      // Get the value of const_item with conversion from DATETIME to TIME
      Time tm(get_thd(), const_item, Time::Options_cmp(thd, mode));
      if (!tm.is_valid_time())
        return NULL;
      /*
        Replace a DATE/DATETIME constant to a TIME constant:
          WHERE LENGTH(time_column)=8
            AND time_column=TIMESTAMP'2015-08-30 10:20:30';
        to:
          WHERE LENGTH(time_column)=10
            AND time_column=TIME'10:20:30'

        (assuming CURRENT_DATE is '2015-08-30'
      */
      return new (thd->mem_root) Item_time_literal(thd, &tm,
                                                   tm.get_mysql_time()->
                                                   second_part ?
                                                   TIME_SECOND_PART_DIGITS :
                                                   0);
    }
    break;
   case IDENTITY_SUBST:
    if (const_item->field_type() != MYSQL_TYPE_TIME ||
        const_item->decimals != decimals())
    {
      /*
        Note, the value returned in "ltime" can have more fractional
        digits that decimals(). The Item_time_literal constructor will
        truncate these digits. We could disallow propagation is such
        cases, but it's still useful (and safe) to optimize:
          WHERE time0_column='00:00:00.123' AND LENGTH(a)=12
        to
          WHERE time0_column='00:00:00.123' AND LENGTH(TIME'00:00:00')=12
        and then to
          WHERE FALSE
        The original WHERE would do the full table scan (in case of no keys).
        The optimized WHERE will return with "Impossible WHERE", without
        having to do the full table scan.
      */
      Time tm(thd, const_item, Time::Options(TIME_TIME_ONLY, thd, mode),
              decimals());
      if (!tm.is_valid_time())
        return NULL;
      return new (thd->mem_root) Item_time_literal(thd, &tm, decimals());
    }
    break;
  }
  return const_item;
}


longlong Field_time_with_dec::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  MYSQL_TIME ltime;
  get_date(&ltime, Time::Options(TIME_TIME_ONLY, get_thd()));
  longlong val= TIME_to_ulonglong_time(&ltime);
  return ltime.neg ? -val : val;
}

double Field_time_with_dec::val_real(void)
{
  DBUG_ASSERT(marked_for_read());
  MYSQL_TIME ltime;
  get_date(&ltime, Time::Options(TIME_TIME_ONLY, get_thd()));
  return TIME_to_double(&ltime);
}

bool Field_time_hires::get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate)
{
  if (check_zero_in_date_with_warn(fuzzydate))
    return true;
  uint32 len= pack_length();
  longlong packed= read_bigendian(ptr, len);

  packed= sec_part_unshift(packed - zero_point, dec);

  unpack_time(packed, ltime, MYSQL_TIMESTAMP_TIME);
  return false;
}


int Field_time_hires::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  ulonglong a=read_bigendian(a_ptr, Field_time_hires::pack_length());
  ulonglong b=read_bigendian(b_ptr, Field_time_hires::pack_length());
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

void Field_time_hires::sort_string(uchar *to,uint length __attribute__((unused)))
{
  DBUG_ASSERT(length == Field_time_hires::pack_length());
  memcpy(to, ptr, length);
  to[0]^= 128;
}

void Field_time_with_dec::make_send_field(Send_field *field)
{
  Field::make_send_field(field);
  field->decimals= dec;
}

/****************************************************************************
** time type with fsp (MySQL-5.6 version)
** In string context: HH:MM:SS.FFFFFF
** In number context: HHMMSS.FFFFFF
****************************************************************************/

int Field_timef::reset()
{
  my_time_packed_to_binary(0, ptr, dec);
  return 0;
}

void Field_timef::store_TIME(const MYSQL_TIME *ltime)
{
  longlong tmp= TIME_to_longlong_time_packed(ltime);
  my_time_packed_to_binary(tmp, ptr, dec);
}

bool Field_timef::get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate)
{
  if (check_zero_in_date_with_warn(fuzzydate))
    return true;
  longlong tmp= my_time_packed_from_binary(ptr, dec);
  TIME_from_longlong_time_packed(ltime, tmp);
  return false;
}
Binlog_type_info Field_timef::binlog_type_info() const
{
  return Binlog_type_info(Field_timef::binlog_type(), decimals(), 1);
}


longlong Field_timef::val_time_packed(THD *thd)
{
  DBUG_ASSERT(marked_for_read());
  longlong tmp= my_time_packed_from_binary(ptr, dec);
  MYSQL_TIME ltime;
  TIME_from_longlong_time_packed(&ltime, tmp);
  return pack_time(&ltime);
}


int Field_timef::store_native(const Native &value)
{
  DBUG_ASSERT(value.length() == my_time_binary_length(dec));
  DBUG_ASSERT(Time(value).is_valid_time());
  memcpy(ptr, value.ptr(), value.length());
  return 0;
}


bool Field_timef::val_native(Native *to)
{
  uint32 binlen= my_time_binary_length(dec);
  return to->copy((const char*) ptr, binlen);
}


/****************************************************************************
** year type
** Save in a byte the year 0, 1901->2155
** Can handle 2 byte or 4 byte years!
****************************************************************************/

int Field_year::store(const char *from, size_t len,CHARSET_INFO *cs)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  THD *thd= get_thd();
  char *end;
  int error;
  longlong nr= cs->strntoull10rnd(from, len, 0, &end, &error);

  if (nr < 0 || (nr >= 100 && nr <= 1900) || nr > 2155 || 
      error == MY_ERRNO_ERANGE)
  {
    *ptr=0;
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
    return 1;
  }

  if (thd->count_cuted_fields <= CHECK_FIELD_EXPRESSION && error == MY_ERRNO_EDOM)
  {
    *ptr= 0;
    return 1;
  }

  if (thd->count_cuted_fields > CHECK_FIELD_EXPRESSION && 
      (error= check_int(cs, from, len, end, error)))
  {
    if (unlikely(error == 1)  /* empty or incorrect string */)
    {
      *ptr= 0;
      return 1;
    }
    error= 1;
  }

  if (nr != 0 || len != 4)
  {
    if (nr < YY_PART_YEAR)
      nr+=100;					// 2000 - 2069
    else if (nr > 1900)
      nr-= 1900;
  }
  *ptr= (char) (uchar) nr;
  return error;
}


int Field_year::store(double nr)
{
  if (nr < 0.0 || nr > 2155.0)
  {
    (void) Field_year::store((longlong) -1, FALSE);
    return 1;
  }
  return Field_year::store((longlong) nr, FALSE);
}


int Field_year::store(longlong nr, bool unsigned_val)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  if (nr < 0 || (nr >= 100 && nr <= 1900) || nr > 2155)
  {
    *ptr= 0;
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
    return 1;
  }
  if (nr != 0 || field_length != 4)		// 0000 -> 0; 00 -> 2000
  {
    if (nr < YY_PART_YEAR)
      nr+=100;					// 2000 - 2069
    else if (nr > 1900)
      nr-= 1900;
  }
  *ptr= (char) (uchar) nr;
  return 0;
}


int Field_year::store_time_dec(const MYSQL_TIME *ltime, uint dec_arg)
{
  ErrConvTime str(ltime);
  if (Field_year::store(ltime->year, 0))
    return 1;

  const char *typestr= Temporal::type_name_by_timestamp_type(ltime->time_type);
  set_datetime_warning(WARN_DATA_TRUNCATED, &str, typestr, 1);
  return 0;
}

bool Field_year::send(Protocol *protocol)
{
  DBUG_ASSERT(marked_for_read());
  Protocol_text *txt;
  if ((txt= dynamic_cast<Protocol_text*>(protocol)))
    return send_numeric_zerofill_str(txt, PROTOCOL_SEND_SHORT);
  ulonglong tmp= Field_year::val_int();
  return protocol->store_short(tmp);
}


double Field_year::val_real(void)
{
  return (double) Field_year::val_int();
}


longlong Field_year::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  DBUG_ASSERT(field_length == 2 || field_length == 4);
  int tmp= (int) ptr[0];
  if (field_length != 4)
    tmp%=100;					// Return last 2 char
  else if (tmp)
    tmp+=1900;
  return (longlong) tmp;
}


String *Field_year::val_str(String *val_buffer,
			    String *val_ptr __attribute__((unused)))
{
  DBUG_ASSERT(field_length < 5);
  val_buffer->alloc(5);
  val_buffer->length(field_length);
  char *to=(char*) val_buffer->ptr();
  sprintf(to,field_length == 2 ? "%02d" : "%04d",(int) Field_year::val_int());
  val_buffer->set_charset(&my_charset_numeric);
  return val_buffer;
}


bool Field_year::get_date(MYSQL_TIME *ltime,date_mode_t fuzzydate)
{
  int tmp= (int) ptr[0];
  if (tmp || field_length != 4)
    tmp+= 1900;
  return int_to_datetime_with_warn(get_thd(),
                                   Longlong_hybrid(tmp * 10000, true),
                                   ltime, fuzzydate, table->s, field_name.str);
}


void Field_year::sql_type(String &res) const
{
  CHARSET_INFO *cs=res.charset();
  res.length(cs->cset->snprintf(cs,(char*)res.ptr(),res.alloced_length(),
			  "year(%d)",(int) field_length));
}


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

int Field_date_common::store_TIME_with_warning(const Datetime *dt,
                                               const ErrConv *str,
                                               int was_cut)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  // Handle totally bad values
  if (!dt->is_valid_datetime())
    return store_invalid_with_warning(str, was_cut, "date");
  // Store the value
  if (!dt->hhmmssff_is_zero())
    was_cut|= MYSQL_TIME_NOTE_TRUNCATED;
  store_datetime(*dt);
  // Caclulate return value and send warnings if needed
  return store_TIME_return_code_with_warnings(was_cut, str, "date");
}

int Field_date_common::store(const char *from, size_t len, CHARSET_INFO *cs)
{
  MYSQL_TIME_STATUS st;
  ErrConvString str(from, len, cs);
  THD *thd= get_thd();
  Datetime dt(thd, &st, from, len, cs, Date::Options(thd), 0);
  return store_TIME_with_warning(&dt, &str, st.warnings);
}

int Field_date_common::store(double nr)
{
  int error;
  ErrConvDouble str(nr);
  THD *thd= get_thd();
  Datetime dt(thd, &error, nr, Date::Options(thd), 0);
  return store_TIME_with_warning(&dt, &str, error);
}

int Field_date_common::store(longlong nr, bool unsigned_val)
{
  int error;
  Longlong_hybrid tmp(nr, unsigned_val);
  ErrConvInteger str(tmp);
  THD *thd= get_thd();
  Datetime dt(&error, tmp, Date::Options(thd));
  return store_TIME_with_warning(&dt, &str, error);
}

int Field_date_common::store_time_dec(const MYSQL_TIME *ltime, uint dec)
{
  int error;
  ErrConvTime str(ltime);
  THD *thd= get_thd();
  Datetime dt(thd, &error, ltime, Date::Options(thd), 0);
  return store_TIME_with_warning(&dt, &str, error);
}

int Field_date_common::store_decimal(const my_decimal *d)
{
  int error;
  ErrConvDecimal str(d);
  THD *thd= get_thd();
  Datetime tm(thd, &error, d, Date::Options(thd), 0);
  return store_TIME_with_warning(&tm, &str, error);
}


/****************************************************************************
** date type
** In string context: YYYY-MM-DD
** In number context: YYYYMMDD
** Stored as a 4 byte unsigned int
****************************************************************************/

void Field_date::store_TIME(const MYSQL_TIME *ltime)
{
  uint tmp= ltime->year*10000L + ltime->month*100+ltime->day;
  int4store(ptr,tmp);
}

bool Field_date::send(Protocol *protocol)
{
  longlong tmp= Field_date::val_int();
  MYSQL_TIME tm;
  tm.year= (uint32) tmp/10000L % 10000;
  tm.month= (uint32) tmp/100 % 100;
  tm.day= (uint32) tmp % 100;
  return protocol->store_date(&tm);
}


double Field_date::val_real(void)
{
  DBUG_ASSERT(marked_for_read());
  int32 j;
  j=sint4korr(ptr);
  return (double) (uint32) j;
}


longlong Field_date::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  int32 j;
  j=sint4korr(ptr);
  return (longlong) (uint32) j;
}


bool Field_date::get_TIME(MYSQL_TIME *ltime, const uchar *pos,
                          date_mode_t fuzzydate) const
{
  DBUG_ASSERT(marked_for_read());
  int32 tmp= sint4korr(pos);
  ltime->year= (int) ((uint32) tmp/10000L % 10000);
  ltime->month= (int) ((uint32) tmp/100 % 100);
  ltime->day= (int) ((uint32) tmp % 100);
  ltime->time_type= MYSQL_TIMESTAMP_DATE;
  ltime->hour= ltime->minute= ltime->second= ltime->second_part= ltime->neg= 0;
  return validate_MMDD(tmp, ltime->month, ltime->day, fuzzydate);
}


String *Field_date::val_str(String *val_buffer,
			    String *val_ptr __attribute__((unused)))
{
  MYSQL_TIME ltime;
  get_TIME(&ltime, ptr, date_mode_t(0));
  val_buffer->alloc(MAX_DATE_STRING_REP_LENGTH);
  uint length= (uint) my_date_to_str(&ltime,
                                     const_cast<char*>(val_buffer->ptr()));
  val_buffer->length(length);
  val_buffer->set_charset(&my_charset_numeric);

  return val_buffer;
}


int Field_date::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  int32 a,b;
  a=sint4korr(a_ptr);
  b=sint4korr(b_ptr);
  return ((uint32) a < (uint32) b) ? -1 : ((uint32) a > (uint32) b) ? 1 : 0;
}


void Field_date::sort_string(uchar *to,uint length __attribute__((unused)))
{
  to[0] = ptr[3];
  to[1] = ptr[2];
  to[2] = ptr[1];
  to[3] = ptr[0];
}

void Field_date::sql_type(String &res) const
{
  res.set_ascii(STRING_WITH_LEN("date"));
}


/****************************************************************************
** The new date type
** This is identical to the old date type, but stored on 3 bytes instead of 4
** In number context: YYYYMMDD
****************************************************************************/

void Field_newdate::store_TIME(const MYSQL_TIME *ltime)
{
  uint tmp= ltime->year*16*32 + ltime->month*32+ltime->day;
  int3store(ptr,tmp);
}


bool Field_newdate::send(Protocol *protocol)
{
  MYSQL_TIME tm;
  Field_newdate::get_date(&tm, date_mode_t(0));
  return protocol->store_date(&tm);
}


double Field_newdate::val_real(void)
{
  DBUG_ASSERT(marked_for_read());
  return (double) Field_newdate::val_int();
}


longlong Field_newdate::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  ulong j= uint3korr(ptr);
  j= (j % 32L)+(j / 32L % 16L)*100L + (j/(16L*32L))*10000L;
  return (longlong) j;
}


String *Field_newdate::val_str(String *val_buffer,
			       String *val_ptr __attribute__((unused)))
{
  DBUG_ASSERT(marked_for_read());
  val_buffer->alloc(field_length+1);
  val_buffer->length(field_length);
  uint32 tmp=(uint32) uint3korr(ptr);
  int part;
  char *pos=(char*) val_buffer->ptr()+10;

  /* Open coded to get more speed */
  *pos--=0;					// End NULL
  part=(int) (tmp & 31);
  *pos--= (char) ('0'+part%10);
  *pos--= (char) ('0'+part/10);
  *pos--= '-';
  part=(int) (tmp >> 5 & 15);
  *pos--= (char) ('0'+part%10);
  *pos--= (char) ('0'+part/10);
  *pos--= '-';
  part=(int) (tmp >> 9);
  *pos--= (char) ('0'+part%10); part/=10;
  *pos--= (char) ('0'+part%10); part/=10;
  *pos--= (char) ('0'+part%10); part/=10;
  *pos=   (char) ('0'+part);
  val_buffer->set_charset(&my_charset_numeric);
  return val_buffer;
}


bool Field_newdate::get_TIME(MYSQL_TIME *ltime, const uchar *pos,
                             date_mode_t fuzzydate) const
{
  DBUG_ASSERT(marked_for_read());
  uint32 tmp=(uint32) uint3korr(pos);
  ltime->day=   tmp & 31;
  ltime->month= (tmp >> 5) & 15;
  ltime->year=  (tmp >> 9);
  ltime->time_type= MYSQL_TIMESTAMP_DATE;
  ltime->hour= ltime->minute= ltime->second= ltime->second_part= ltime->neg= 0;
  return validate_MMDD(tmp, ltime->month, ltime->day, fuzzydate);
}


longlong Field_newdate::val_datetime_packed(THD *thd)
{
  MYSQL_TIME ltime;
  Field_newdate::get_date(&ltime, date_mode_t(0));
  return pack_time(&ltime);
}


int Field_newdate::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  uint32 a,b;
  a=(uint32) uint3korr(a_ptr);
  b=(uint32) uint3korr(b_ptr);
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}


void Field_newdate::sort_string(uchar *to,uint length __attribute__((unused)))
{
  to[0] = ptr[2];
  to[1] = ptr[1];
  to[2] = ptr[0];
}


void Field_newdate::sql_type(String &res) const
{
  res.set_ascii(STRING_WITH_LEN("date"));
}


Item *Field_newdate::get_equal_const_item(THD *thd, const Context &ctx,
                                          Item *const_item)
{
  switch (ctx.subst_constraint()) {
  case ANY_SUBST:
    if (!is_temporal_type_with_date(const_item->field_type()))
    {
      /*
        DATE is compared to DATETIME-alike non-temporal values
        (such as VARCHAR, DECIMAL) as DATETIME, e.g.:
          WHERE date_column=20010101235959.0000009
        So here we convert the constant to DATETIME normally.
        In case if TIME_ROUND_FRACTIONAL is enabled, nanoseconds will round.
      */
      Datetime dt(thd, const_item, Datetime::Options_cmp(thd));
      if (!dt.is_valid_datetime())
        return NULL;
      /*
        Replace the constant to a DATE or DATETIME constant.
        Example:
          WHERE LENGTH(date_column)=10
            AND date_column=TIME'10:20:30';
        to:
          WHERE LENGTH(date_column)=10
            AND date_column=TIMESTAMP'2015-08-30 10:20:30'

        (assuming CURRENT_DATE is '2015-08-30'
      */
      if (!dt.hhmmssff_is_zero())
        return new (thd->mem_root)
          Item_datetime_literal_for_invalid_dates(thd, &dt,
                                                  dt.get_mysql_time()->
                                                    second_part ?
                                                  TIME_SECOND_PART_DIGITS : 0);
      Date d(&dt);
      return new (thd->mem_root) Item_date_literal_for_invalid_dates(thd, &d);
    }
    break;
  case IDENTITY_SUBST:
    if (const_item->field_type() != MYSQL_TYPE_DATE)
    {
      /*
        DATE is compared to non-temporal as DATETIME.
        We need to convert to DATETIME first, taking into account the
        current session rounding mode (even though this is IDENTITY_SUBSTS!),
        then convert the result to DATE.
      */
      Datetime dt(thd, const_item, Datetime::Options(TIME_CONV_NONE, thd));
      if (!dt.is_valid_datetime())
        return NULL;
      Date d(&dt);
      return new (thd->mem_root) Item_date_literal(thd, &d);
    }
    break;
  }
  return const_item;
}


/****************************************************************************
** datetime type
** In string context: YYYY-MM-DD HH:MM:DD
** In number context: YYYYMMDDHHMMDD
** Stored as a 8 byte unsigned int. Should sometimes be change to a 6 byte int.
****************************************************************************/

void Field_datetime0::store_TIME(const MYSQL_TIME *ltime)
{
  ulonglong tmp= TIME_to_ulonglong_datetime(ltime);
  int8store(ptr,tmp);
}


sql_mode_t
Field_datetime::conversion_depends_on_sql_mode(THD *thd, Item *expr) const
{
  return expr->datetime_precision(thd) > decimals() ?
         MODE_TIME_ROUND_FRACTIONAL : 0;
}


bool Field_datetime0::send(Protocol *protocol)
{
  MYSQL_TIME tm;
  Field_datetime0::get_date(&tm, date_mode_t(0));
  return protocol->store_datetime(&tm, 0);
}


longlong Field_datetime0::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  longlong j;
  j=sint8korr(ptr);
  return j;
}


String *Field_datetime0::val_str(String *val_buffer,
                                 String *val_ptr __attribute__((unused)))
{
  val_buffer->alloc(field_length+1);
  val_buffer->length(field_length);

  DBUG_ASSERT(marked_for_read());
  ulonglong tmp;
  long part1,part2;
  char *pos;
  int part3;

  tmp= Field_datetime0::val_int();

  /*
    Avoid problem with slow longlong arithmetic and sprintf
  */

  part1=(long) (tmp/1000000LL);
  part2=(long) (tmp - (ulonglong) part1*1000000LL);

  pos=(char*) val_buffer->ptr() + MAX_DATETIME_WIDTH;
  *pos--=0;
  *pos--= (char) ('0'+(char) (part2%10)); part2/=10;
  *pos--= (char) ('0'+(char) (part2%10)); part3= (int) (part2 / 10);
  *pos--= ':';
  *pos--= (char) ('0'+(char) (part3%10)); part3/=10;
  *pos--= (char) ('0'+(char) (part3%10)); part3/=10;
  *pos--= ':';
  *pos--= (char) ('0'+(char) (part3%10)); part3/=10;
  *pos--= (char) ('0'+(char) part3);
  *pos--= ' ';
  *pos--= (char) ('0'+(char) (part1%10)); part1/=10;
  *pos--= (char) ('0'+(char) (part1%10)); part1/=10;
  *pos--= '-';
  *pos--= (char) ('0'+(char) (part1%10)); part1/=10;
  *pos--= (char) ('0'+(char) (part1%10)); part3= (int) (part1/10);
  *pos--= '-';
  *pos--= (char) ('0'+(char) (part3%10)); part3/=10;
  *pos--= (char) ('0'+(char) (part3%10)); part3/=10;
  *pos--= (char) ('0'+(char) (part3%10)); part3/=10;
  *pos=(char) ('0'+(char) part3);
  val_buffer->set_charset(&my_charset_numeric);
  return val_buffer;
}

bool Field_datetime0::get_TIME(MYSQL_TIME *ltime, const uchar *pos,
                               date_mode_t fuzzydate) const
{
  DBUG_ASSERT(marked_for_read());
  longlong tmp= sint8korr(pos);
  uint32 part1,part2;
  part1=(uint32) (tmp/1000000LL);
  part2=(uint32) (tmp - (ulonglong) part1*1000000LL);

  ltime->time_type=	MYSQL_TIMESTAMP_DATETIME;
  ltime->neg=		0;
  ltime->second_part=	0;
  ltime->second=	(int) (part2%100);
  ltime->minute=	(int) (part2/100%100);
  ltime->hour=		(int) (part2/10000);
  ltime->day=		(int) (part1%100);
  ltime->month= 	(int) (part1/100%100);
  ltime->year= 		(int) (part1/10000);
  return validate_MMDD(tmp, ltime->month, ltime->day, fuzzydate);
}


int Field_datetime0::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  longlong a,b;
  a=sint8korr(a_ptr);
  b=sint8korr(b_ptr);
  return ((ulonglong) a < (ulonglong) b) ? -1 :
    ((ulonglong) a > (ulonglong) b) ? 1 : 0;
}

void Field_datetime0::sort_string(uchar *to,uint length __attribute__((unused)))
{
  to[0] = ptr[7];
  to[1] = ptr[6];
  to[2] = ptr[5];
  to[3] = ptr[4];
  to[4] = ptr[3];
  to[5] = ptr[2];
  to[6] = ptr[1];
  to[7] = ptr[0];
}


int Field_datetime::set_time()
{
  THD *thd= table->in_use;
  set_notnull();
  // Here we always truncate (not round), no matter what sql_mode is
  if (decimals())
    store_datetime(Datetime(thd, Timeval(thd->query_start(),
                                         thd->query_start_sec_part())
                            ).trunc(decimals()));
  else
    store_datetime(Datetime(thd, Timeval(thd->query_start(), 0)));
  return 0;
}


void Field_datetime_hires::store_TIME(const MYSQL_TIME *ltime)
{
  ulonglong packed= sec_part_shift(pack_time(ltime), dec);
  store_bigendian(packed, ptr, Field_datetime_hires::pack_length());
}

bool Field_datetime_with_dec::send(Protocol *protocol)
{
  MYSQL_TIME ltime;
  get_date(&ltime, date_mode_t(0));
  return protocol->store_datetime(&ltime, dec);
}


double Field_datetime_with_dec::val_real(void)
{
  MYSQL_TIME ltime;
  get_date(&ltime, date_mode_t(0));
  return TIME_to_double(&ltime);
}

longlong Field_datetime_with_dec::val_int(void)
{
  MYSQL_TIME ltime;
  get_date(&ltime, date_mode_t(0));
  return TIME_to_ulonglong_datetime(&ltime);
}


String *Field_datetime_with_dec::val_str(String *str,
                                         String *unused __attribute__((unused)))
{
  MYSQL_TIME ltime;
  get_date(&ltime, date_mode_t(0));
  str->alloc(field_length+1);
  str->length(field_length);
  my_datetime_to_str(&ltime, (char*) str->ptr(), dec);
  str->set_charset(&my_charset_numeric);
  return str;
}


bool Field_datetime_hires::get_TIME(MYSQL_TIME *ltime, const uchar *pos,
                                    date_mode_t fuzzydate) const
{
  DBUG_ASSERT(marked_for_read());
  ulonglong packed= read_bigendian(pos, Field_datetime_hires::pack_length());
  unpack_time(sec_part_unshift(packed, dec), ltime, MYSQL_TIMESTAMP_DATETIME);
  return validate_MMDD(packed, ltime->month, ltime->day, fuzzydate);
}


int Field_datetime_hires::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  ulonglong a=read_bigendian(a_ptr, Field_datetime_hires::pack_length());
  ulonglong b=read_bigendian(b_ptr, Field_datetime_hires::pack_length());
  return a < b ? -1 : a > b ? 1 : 0;
}

void Field_datetime_with_dec::make_send_field(Send_field *field)
{
  Field::make_send_field(field);
  field->decimals= dec;
}


/****************************************************************************
** MySQL-5.6 compatible DATETIME(N)
**
****************************************************************************/
int Field_datetimef::reset()
{
  my_datetime_packed_to_binary(0, ptr, dec);
  return 0;
}

void Field_datetimef::store_TIME(const MYSQL_TIME *ltime)
{
  longlong tmp= TIME_to_longlong_datetime_packed(ltime);
  my_datetime_packed_to_binary(tmp, ptr, dec);
}

bool Field_datetimef::get_TIME(MYSQL_TIME *ltime, const uchar *pos,
                               date_mode_t fuzzydate) const
{
  DBUG_ASSERT(marked_for_read());
  longlong tmp= my_datetime_packed_from_binary(pos, dec);
  TIME_from_longlong_datetime_packed(ltime, tmp);
  return validate_MMDD(tmp, ltime->month, ltime->day, fuzzydate);
}
Binlog_type_info Field_datetimef::binlog_type_info() const
{
  return Binlog_type_info(Field_datetimef::binlog_type(), decimals(), 1);
}

longlong Field_datetimef::val_datetime_packed(THD *thd)
{
  DBUG_ASSERT(marked_for_read());
  longlong tmp= my_datetime_packed_from_binary(ptr, dec);
  MYSQL_TIME ltime;
  TIME_from_longlong_datetime_packed(&ltime, tmp);
  return pack_time(&ltime);
}


/****************************************************************************
** string type
** A string may be varchar or binary
****************************************************************************/

/*
  Report "not well formed" or "cannot convert" error
  after storing a character string info a field.

  SYNOPSIS
    check_string_copy_error()
    copier                   - the conversion status
    end                      - the very end of the source string
                               that was just copied
    cs                       - character set of the string

  NOTES
    As of version 5.0 both cases return the same error:
  
      "Invalid string value: 'xxx' for column 't' at row 1"
  
  Future versions will possibly introduce a new error message:

      "Cannot convert character string: 'xxx' for column 't' at row 1"

  RETURN
    FALSE - If errors didn't happen
    TRUE  - If an error happened
*/

bool
Field_longstr::check_string_copy_error(const String_copier *copier,
                                       const char *end,
                                       CHARSET_INFO *cs)
{
  const char *pos;
  char tmp[32];

  if (likely(!(pos= copier->most_important_error_pos())))
    return FALSE;

  /* Ignore errors from internal expressions */
  if (get_thd()->count_cuted_fields > CHECK_FIELD_EXPRESSION)
  {
    DBUG_ASSERT(sizeof(tmp) >= convert_to_printable_required_length(6));
    convert_to_printable(tmp, sizeof(tmp), pos, (end - pos), cs, 6);
    set_warning_truncated_wrong_value("string", tmp);
  }
  return TRUE;
}


/*
  Check if we lost any important data and send a truncation error/warning

  SYNOPSIS
    Field_longstr::report_if_important_data()
    pstr                     - Truncated rest of string
    end                      - End of truncated string
    count_spaces             - Treat traling spaces as important data

  RETURN VALUES
    0   - None was truncated (or we don't count cut fields)
    2   - Some bytes was truncated

  NOTE
    Check if we lost any important data (anything in a binary string,
    or any non-space in others). If only trailing spaces was lost,
    send a truncation note, otherwise send a truncation error.
    Silently ignore traling spaces if the count_space parameter is FALSE.
*/

int
Field_longstr::report_if_important_data(const char *pstr, const char *end,
                                        bool count_spaces)
{
  THD *thd;
  if ((pstr < end) &&
      (thd= get_thd())->count_cuted_fields > CHECK_FIELD_EXPRESSION)
  {
    if (test_if_important_data(field_charset(), pstr, end))
    {
      if (thd->abort_on_warning)
        set_warning(ER_DATA_TOO_LONG, 1);
      else
        set_warning(WARN_DATA_TRUNCATED, 1);
      return 2;
    }
    else if (count_spaces)
    {
      /* If we lost only spaces then produce a NOTE, not a WARNING */
      set_note(WARN_DATA_TRUNCATED, 1);
      return 2;
    }
  }
  return 0;
}


/*
  This is JSON specific.
  We should eventually add Field_json_varchar and Field_json_blob
  and move make_send_field() to the new classes.
*/
void Field_longstr::make_send_field(Send_field *field)
{
  Field_str::make_send_field(field);
  if (check_constraint)
  {
    /*
      Append the format that is implicitly implied by the CHECK CONSTRAINT.
      For example:
        CREATE TABLE t1 (js longtext DEFAULT NULL CHECK (json_valid(a)));
        SELECT j FROM t1;
      will add "format=json" to the extended type info metadata for t1.js.
    */
    check_constraint->expr->set_format_by_check_constraint(field);
  }
}


/*
  An optimized version that uses less stack than Field::send().
*/
bool Field_longstr::send(Protocol *protocol)
{
  String tmp;
  val_str(&tmp, &tmp);
  /*
    Ensure this function is only used with classes that do not allocate
    memory in val_str()
  */
  DBUG_ASSERT(tmp.alloced_length() == 0);
  return protocol->store(tmp.ptr(), tmp.length(), tmp.charset());
}


const Type_handler *Field_string::type_handler() const
{
  if (is_var_string())
    return &type_handler_var_string;
  /*
    This is a temporary solution and will be fixed soon (in 10.9?).
    Type_handler_string_json will provide its own Field_string_json.
  */
  if (Type_handler_json_common::has_json_valid_constraint(this))
   return &type_handler_string_json;
  return &type_handler_string;
}

	/* Copy a string and fill with space */

int Field_string::store(const char *from, size_t length,CHARSET_INFO *cs)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  uint copy_length;
  int rc;

  /* See the comment for Field_long::store(long long) */
  DBUG_ASSERT(!table || table->in_use == current_thd);

  rc= well_formed_copy_with_check((char*) ptr, field_length,
                                  cs, from, length,
                                  Field_string::char_length(),
                                  false, &copy_length);

  /* Append spaces if the string was shorter than the field. */
  if (copy_length < field_length)
    field_charset()->fill((char*) ptr + copy_length,
                          field_length - copy_length,
                          field_charset()->pad_char);

  return rc;
}


int Field_str::store(longlong nr, bool unsigned_val)
{
  char buff[64];
  uint  length;
  length= (uint) (field_charset()->longlong10_to_str)(buff, sizeof(buff),
                                                      (unsigned_val ? 10: -10),
                                                      nr);
  return store(buff, length, field_charset());
}


/**
  Store double value in Field_string or Field_varstring.

  Pretty prints double number into field_length characters buffer.

  @param nr            number
*/

int Field_str::store(double nr)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  char buff[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
  uint local_char_length= MY_MIN(sizeof(buff), Field_str::char_length());
  size_t length= 0;
  my_bool error= (local_char_length == 0);

  // my_gcvt() requires width > 0, and we may have a CHAR(0) column.
  if (likely(!error))
    length= my_gcvt(nr, MY_GCVT_ARG_DOUBLE, local_char_length, buff, &error);

  if (unlikely(error))
  {
    if (get_thd()->abort_on_warning)
      set_warning(ER_DATA_TOO_LONG, 1);
    else
      set_warning(WARN_DATA_TRUNCATED, 1);
  }
  return store(buff, (uint)length, &my_charset_numeric);
}

bool Field_string::is_equal(const Column_definition &new_field) const
{
  DBUG_ASSERT(!compression_method());
  return new_field.type_handler() == type_handler() &&
         new_field.char_length == char_length() &&
         new_field.charset == field_charset() &&
         new_field.length == max_display_length();
}


int Field_longstr::store_decimal(const my_decimal *d)
{
  StringBuffer<DECIMAL_MAX_STR_LENGTH+1> str;
  d->to_string(&str);
  return store(str.ptr(), str.length(), str.charset());
}

uint32 Field_longstr::max_data_length() const
{
  return field_length + (field_length > 255 ? 2 : 1);
}


bool
Field_longstr::cmp_to_string_with_same_collation(const Item_bool_func *cond,
                                                 const Item *item) const
{
  return cmp_is_done_using_type_handler_of_this(cond, item) &&
         charset() == cond->compare_collation();
}


bool
Field_longstr::cmp_to_string_with_stricter_collation(const Item_bool_func *cond,
                                                     const Item *item) const
{
  return cmp_is_done_using_type_handler_of_this(cond, item) &&
         (charset() == cond->compare_collation() ||
          cond->compare_collation()->state & MY_CS_BINSORT);
}


bool Field_longstr::can_optimize_keypart_ref(const Item_bool_func *cond,
                                             const Item *item) const
{
  DBUG_ASSERT(cmp_type() == STRING_RESULT);
  return cmp_to_string_with_stricter_collation(cond, item);
}


bool Field_longstr::can_optimize_hash_join(const Item_bool_func *cond,
                                           const Item *item) const
{
  DBUG_ASSERT(cmp_type() == STRING_RESULT);
  return cmp_to_string_with_same_collation(cond, item);
}


bool Field_longstr::can_optimize_group_min_max(const Item_bool_func *cond,
                                               const Item *const_item) const
{
  /*
    Can't use indexes when comparing a string to a number or a date
    Don't use an index when comparing strings of different collations.
  */
  DBUG_ASSERT(cmp_type() == STRING_RESULT);
  return cmp_to_string_with_same_collation(cond, const_item);
}


bool Field_longstr::can_optimize_range(const Item_bool_func *cond,
                                       const Item *item,
                                       bool is_eq_func) const
{
  return is_eq_func ?
         cmp_to_string_with_stricter_collation(cond, item) :
         cmp_to_string_with_same_collation(cond, item);
}


/**
  This overrides the default behavior of the parent constructor
  Warn_filter(thd) to suppress notes about trailing spaces in case of CHAR(N),
  as they are truncated during val_str().
  We still do want truncation notes in case of BINARY(N),
  as trailing spaces are not truncated in val_str().
*/
Field_string::Warn_filter_string::Warn_filter_string(const THD *thd,
                                                     const Field_string *field)
  :Warn_filter(!thd->no_errors,
               !thd->no_errors &&
               field->field_charset() == &my_charset_bin)
{ }


double Field_string::val_real(void)
{
  DBUG_ASSERT(marked_for_read());
  THD *thd= get_thd();
  return Converter_strntod_with_warn(get_thd(),
                                     Warn_filter_string(thd, this),
                                     Field_string::charset(),
                                     (const char *) ptr,
                                     field_length).result();
}


longlong Field_string::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  THD *thd= get_thd();
  return Converter_strntoll_with_warn(thd, Warn_filter_string(thd, this),
                                      Field_string::charset(),
                                      (const char *) ptr,
                                      field_length).result();
}


sql_mode_t Field_string::value_depends_on_sql_mode() const
{
  return has_charset() ? MODE_PAD_CHAR_TO_FULL_LENGTH : sql_mode_t(0);
};


sql_mode_t Field_string::can_handle_sql_mode_dependency_on_store() const
{
  return has_charset() ? MODE_PAD_CHAR_TO_FULL_LENGTH : sql_mode_t(0);
}


String *Field_string::val_str(String *val_buffer __attribute__((unused)),
			      String *val_ptr)
{
  DBUG_ASSERT(marked_for_read());
  /* See the comment for Field_long::store(long long) */
  DBUG_ASSERT(!table || table->in_use == current_thd);
  size_t length;
  if (get_thd()->variables.sql_mode &
      MODE_PAD_CHAR_TO_FULL_LENGTH)
    length= field_charset()->charpos(ptr, ptr + field_length,
                                     Field_string::char_length());
  else
    length= field_charset()->lengthsp((const char*) ptr, field_length);
  val_ptr->set((const char*) ptr, length, field_charset());
  return val_ptr;
}


my_decimal *Field_string::val_decimal(my_decimal *decimal_value)
{
  DBUG_ASSERT(marked_for_read());
  THD *thd= get_thd();
  Converter_str2my_decimal_with_warn(thd,
                                     Warn_filter_string(thd, this),
                                     E_DEC_FATAL_ERROR & ~E_DEC_BAD_NUM,
                                     Field_string::charset(),
                                     (const char *) ptr,
                                     field_length, decimal_value);
  return decimal_value;
}


struct Check_field_param {
  const Field *field;
};

#ifdef HAVE_REPLICATION
static bool
check_field_for_37426(const void *param_arg)
{
  Check_field_param *param= (Check_field_param*) param_arg;
  DBUG_ASSERT(param->field->real_type() == MYSQL_TYPE_STRING);
  DBUG_PRINT("debug", ("Field %s - type: %d, size: %d",
                       param->field->field_name.str,
                       param->field->real_type(),
                       param->field->row_pack_length()));
  return param->field->row_pack_length() > 255;
}
#endif

bool
Field_string::compatible_field_size(uint field_metadata,
                                    const Relay_log_info *rli_arg,
                                    uint16 mflags __attribute__((unused)),
                                    int *order_var) const
{
#ifdef HAVE_REPLICATION
  const Check_field_param check_param = { this };
  if (rpl_master_has_bug(rli_arg, 37426, TRUE,
                         check_field_for_37426, &check_param))
    return FALSE;                        // Not compatible field sizes
#endif
  return Field::compatible_field_size(field_metadata, rli_arg, mflags, order_var);
}


int Field_string::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  return field_charset()->coll->strnncollsp_nchars(field_charset(),
                                                   a_ptr, field_length,
                                                   b_ptr, field_length,
                                                   Field_string::char_length());
}


void Field_string::sort_string(uchar *to,uint length)
{
#ifdef DBUG_ASSERT_EXISTS
  size_t tmp=
#endif
    field_charset()->strnxfrm(to, length,
                              char_length() * field_charset()->strxfrm_multiply,
                              ptr, field_length,
                              MY_STRXFRM_PAD_WITH_SPACE |
                              MY_STRXFRM_PAD_TO_MAXLEN);
  DBUG_ASSERT(tmp == length);
}


void Field_string::sql_type(String &res) const
{
  THD *thd= table->in_use;
  CHARSET_INFO *cs=res.charset();
  size_t length;

  length= cs->cset->snprintf(cs,(char*) res.ptr(),
                             res.alloced_length(), "%s(%d)%s",
                             (type() == MYSQL_TYPE_VAR_STRING ?
                              (has_charset() ? "varchar" : "varbinary") :
			      (has_charset() ? "char" : "binary")),
                             (int) field_length / charset()->mbmaxlen,
                             type() == MYSQL_TYPE_VAR_STRING ? "/*old*/" : "");
  res.length(length);
  if ((thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40)) &&
      has_charset() && (charset()->state & MY_CS_BINSORT))
    res.append(STRING_WITH_LEN(" binary"));
}

/**
   For fields which are associated with character sets their length is provided
   in octets and their character set information is also provided as part of
   type information.

   @param   res       String which contains filed type and length.
*/
void Field_string::sql_rpl_type(String *res) const
{
  CHARSET_INFO *cs=charset();
  if (Field_string::has_charset())
  {
    size_t length= cs->cset->snprintf(cs, (char*) res->ptr(),
                                      res->alloced_length(),
                                      "char(%u octets) character set %s",
                                      field_length,
                                      charset()->cs_name.str);
    res->length(length);
  }
  else
    Field_string::sql_type(*res);
 }

uchar *Field_string::pack(uchar *to, const uchar *from, uint max_length)
{
  DBUG_PRINT("debug", ("Packing field '%s'", field_name.str));
  return StringPack(field_charset(), field_length).pack(to, from, max_length);
}


/**
   Unpack a string field from row data.

   This method is used to unpack a string field from a master whose size 
   of the field is less than that of the slave. Note that there can be a
   variety of field types represented with this class. Certain types like
   ENUM or SET are processed differently. Hence, the upper byte of the 
   @c param_data argument contains the result of field->real_type() from
   the master.

   @note For information about how the length is packed, see @c
   Field_string::save_field_metadata

   @param   to         Destination of the data
   @param   from       Source of the data
   @param   param_data Real type (upper) and length (lower) values

   @return  New pointer into memory based on from + length of the data
*/
const uchar *
Field_string::unpack(uchar *to, const uchar *from, const uchar *from_end,
                     uint param_data)
{
  return StringPack(field_charset(), field_length).unpack(to, from, from_end,
                                                          param_data);
}


/**
   Save the field metadata for string fields.

   Saves the real type in the first byte and the field length in the 
   second byte of the field metadata array at index of *metadata_ptr and
   *(metadata_ptr + 1).

   @note In order to be able to handle lengths exceeding 255 and be
   backwards-compatible with pre-5.1.26 servers, an extra two bits of
   the length has been added to the metadata in such a way that if
   they are set, a new unrecognized type is generated.  This will
   cause pre-5.1-26 servers to stop due to a field type mismatch,
   while new servers will be able to extract the extra bits. If the
   length is <256, there will be no difference and both a new and an
   old server will be able to handle it.

   @note The extra two bits are added to bits 13 and 14 of the
   parameter data (with 1 being the least siginficant bit and 16 the
   most significant bit of the word) by xoring the extra length bits
   with the real type.  Since all allowable types have 0xF as most
   significant bits of the metadata word, lengths <256 will not affect
   the real type at all, while all other values will result in a
   non-existent type in the range 17-244.

   @see Field_string::unpack

   @param   metadata_ptr   First byte of field metadata

   @returns number of bytes written to metadata_ptr
*/

Binlog_type_info_fixed_string::Binlog_type_info_fixed_string(uchar type_code,
                                                             uint32 octets,
                                                             CHARSET_INFO *cs)
 :Binlog_type_info(type_code, 0, 2, cs)
{
  DBUG_ASSERT(octets < 1024);
  DBUG_ASSERT((type_code & 0xF0) == 0xF0);
  DBUG_PRINT("debug", ("octets: %u, type_code: %u", octets, type_code));
  m_metadata= (type_code ^ ((octets & 0x300) >> 4)) +
              (((uint)(octets & 0xFF)) << 8);
}


Binlog_type_info Field_string::binlog_type_info() const
{
  DBUG_ASSERT(Field_string::type() == binlog_type());
  return Binlog_type_info_fixed_string(Field_string::binlog_type(),
                                       field_length, charset());
}


uint Field_string::packed_col_length(const uchar *data_ptr, uint length)
{
  return StringPack::packed_col_length(data_ptr, length);
}


uint Field_string::max_packed_col_length(uint max_length)
{
  return StringPack::max_packed_col_length(max_length);
}


uint Field_string::get_key_image(uchar *buff, uint length, const uchar *ptr_arg,
                                 imagetype type_arg) const
{
  size_t bytes= field_charset()->charpos((char*) ptr_arg,
                                         (char*) ptr_arg + field_length,
                                         length / mbmaxlen());
  memcpy(buff, ptr_arg, bytes);
  if (bytes < length)
    field_charset()->fill((char*) buff + bytes,
                          length - bytes,
                          field_charset()->pad_char);
  return (uint)bytes;
}


Field *Field_string::make_new_field(MEM_ROOT *root, TABLE *new_table,
                                    bool keep_type)
{
  Field *field;
  if (type() != MYSQL_TYPE_VAR_STRING || keep_type)
    field= Field::make_new_field(root, new_table, keep_type);
  else if ((field= new (root) Field_varstring(field_length, maybe_null(),
                                              &field_name,
                                              new_table->s, charset())))
  {
    /*
      Old VARCHAR field which should be modified to a VARCHAR on copy
      This is done to ensure that ALTER TABLE will convert old VARCHAR fields
      to now VARCHAR fields.
    */
    field->init_for_make_new_field(new_table, orig_table);
  }
  return field;
}


en_fieldtype Field_string::tmp_engine_column_type(bool use_packed_rows) const
{
  return field_length >= MIN_STRING_LENGTH_TO_PACK_ROWS ? FIELD_SKIP_ENDSPACE :
                                                          FIELD_NORMAL;
}

/****************************************************************************
  VARCHAR type
  Data in field->ptr is stored as:
    1 or 2 bytes length-prefix-header  (from Field_varstring::length_bytes)
    data

  NOTE:
  When VARCHAR is stored in a key (for handler::index_read() etc) it's always
  stored with a 2 byte prefix. (Just like blob keys).

  Normally length_bytes is calculated as (field_length < 256 : 1 ? 2)
  The exception is if there is a prefix key field that is part of a long
  VARCHAR, in which case field_length for this may be 1 but the length_bytes
  is 2.
****************************************************************************/

const uint Field_varstring::MAX_SIZE= UINT_MAX16;


const Type_handler *Field_varstring::type_handler() const
{
  /*
    This is a temporary solution and will be fixed soon (in 10.9?).
    Type_handler_varchar_json will provide its own Field_varstring_json
    and Field_varstring_compressed_json
  */
  if (Type_handler_json_common::has_json_valid_constraint(this))
    return &type_handler_varchar_json;
  return &type_handler_varchar;
}


/**
   Save the field metadata for varstring fields.

   Saves the field length in the first byte. Note: may consume
   2 bytes. Caller must ensure second byte is contiguous with
   first byte (e.g. array index 0,1).

   @param   metadata_ptr   First byte of field metadata

   @returns number of bytes written to metadata_ptr
*/
Binlog_type_info Field_varstring::binlog_type_info() const
{
  DBUG_ASSERT(Field_varstring::type() == binlog_type());
  return Binlog_type_info(Field_varstring::type(), field_length, 2, charset());
}


bool Field_varstring::memcpy_field_possible(const Field *from) const
{
  return (Field_str::memcpy_field_possible(from) &&
          !compression_method() == !from->compression_method() &&
          length_bytes == ((Field_varstring*) from)->length_bytes &&
          (table->file && !(table->file->ha_table_flags() &
                            HA_RECORD_MUST_BE_CLEAN_ON_WRITE)));
}


int Field_varstring::store(const char *from,size_t length,CHARSET_INFO *cs)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  uint copy_length;
  int rc;

  rc= well_formed_copy_with_check((char*) get_data(), field_length,
                                  cs, from, length,
                                  Field_varstring::char_length(),
                                  true, &copy_length);

  store_length(copy_length);

  return rc;
}


double Field_varstring::val_real(void)
{
  DBUG_ASSERT(marked_for_read());
  THD *thd= get_thd();
  return Converter_strntod_with_warn(thd, Warn_filter(thd),
                                     Field_varstring::charset(),
                                     (const char *) get_data(),
                                     get_length()).result();
}


longlong Field_varstring::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  THD *thd= get_thd();
  return Converter_strntoll_with_warn(thd, Warn_filter(thd),
                                      Field_varstring::charset(),
                                      (const char *) get_data(),
                                      get_length()).result();
}


String *Field_varstring::val_str(String *val_buffer __attribute__((unused)),
				 String *val_ptr)
{
  DBUG_ASSERT(marked_for_read());
  val_ptr->set((const char*) get_data(), get_length(), field_charset());
  return val_ptr;
}


my_decimal *Field_varstring::val_decimal(my_decimal *decimal_value)
{
  DBUG_ASSERT(marked_for_read());
  THD *thd= get_thd();
  Converter_str2my_decimal_with_warn(thd, Warn_filter(thd),
                                     E_DEC_FATAL_ERROR & ~E_DEC_BAD_NUM,
                                     Field_varstring::charset(),
                                     (const char *) get_data(),
                                     get_length(), decimal_value);
  return decimal_value;

}


/*
  An optimized version that uses less stack and less temporary
  variable initialization than Field_longstr::send()
*/
bool Field_varstring::send(Protocol *protocol)
{
  return protocol->store((const char *) get_data(), get_length(),
                         field_charset());
}


#ifdef HAVE_MEM_CHECK

/*
  Mark the unused part of the varstring as defined.

  This function is only used be Unique when calculating statistics.

  The marking is needed as we write the whole tree to disk in case of
  overflows.  For using or comparing values the undefined value part
  is never used. We could also use bzero() here, but it would be
  slower in production environments.
  This function is tested by main.stat_tables-enospc
*/

void Field_varstring::mark_unused_memory_as_defined()
{
  uint used_length __attribute__((unused)) = get_length();
  MEM_MAKE_DEFINED(get_data() + used_length, field_length - used_length);
}
#endif


int Field_varstring::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  uint a_length, b_length;
  int diff;

  if (length_bytes == 1)
  {
    a_length= (uint) *a_ptr;
    b_length= (uint) *b_ptr;
  }
  else
  {
    a_length= uint2korr(a_ptr);
    b_length= uint2korr(b_ptr);
  }
  set_if_smaller(a_length, field_length);
  set_if_smaller(b_length, field_length);
  diff= field_charset()->strnncollsp(a_ptr + length_bytes, a_length,
                                     b_ptr + length_bytes, b_length);
  return diff;
}


int Field_varstring::cmp_prefix(const uchar *a_ptr, const uchar *b_ptr,
                                size_t prefix_len) const
{
  /* avoid expensive well_formed_char_length if possible */
  if (prefix_len == table->field[field_index]->field_length)
    return Field_varstring::cmp(a_ptr, b_ptr);

  size_t a_length, b_length;

  if (length_bytes == 1)
  {
    a_length= *a_ptr;
    b_length= *b_ptr;
  }
  else
  {
    a_length= uint2korr(a_ptr);
    b_length= uint2korr(b_ptr);
  }
  return field_charset()->coll->strnncollsp_nchars(field_charset(),
                                                   a_ptr + length_bytes,
                                                   a_length,
                                                   b_ptr + length_bytes,
                                                   b_length,
                                                   prefix_len /
                                                     field_charset()->mbmaxlen);
}


/**
  @note
    varstring and blob keys are ALWAYS stored with a 2 byte length prefix
*/

int Field_varstring::key_cmp(const uchar *key_ptr, uint max_key_length) const
{
  size_t length=  length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
  size_t local_char_length= max_key_length / mbmaxlen();

  local_char_length= field_charset()->charpos(ptr + length_bytes,
                                              ptr + length_bytes + length,
                                              local_char_length);
  set_if_smaller(length, local_char_length);
  return field_charset()->strnncollsp(ptr + length_bytes,
                                      length,
                                      key_ptr + HA_KEY_BLOB_LENGTH,
                                      uint2korr(key_ptr));
}


/**
  Compare to key segments (always 2 byte length prefix).

  @note
    This is used only to compare key segments created for index_read().
    (keys are created and compared in key.cc)
*/

int Field_varstring::key_cmp(const uchar *a,const uchar *b) const
{
  return field_charset()->strnncollsp(a + HA_KEY_BLOB_LENGTH, uint2korr(a),
                                      b + HA_KEY_BLOB_LENGTH, uint2korr(b));
}


void Field_varstring::sort_string(uchar *to,uint length)
{
  String buf;

  val_str(&buf, &buf);

  if (field_charset() == &my_charset_bin)
  {
    /* Store length last in high-byte order to sort longer strings first */
    if (length_bytes == 1)
      to[length - 1]= buf.length();
    else
      mi_int2store(to + length - 2, buf.length());
    length-= length_bytes;
  }

#ifdef DBUG_ASSERT_EXISTS
    size_t rc=
#endif
  field_charset()->strnxfrm(to, length,
                            char_length() * field_charset()->strxfrm_multiply,
                            (const uchar *) buf.ptr(), buf.length(),
                            MY_STRXFRM_PAD_WITH_SPACE |
                            MY_STRXFRM_PAD_TO_MAXLEN);
  DBUG_ASSERT(rc == length);
}


enum ha_base_keytype Field_varstring::key_type() const
{
  enum ha_base_keytype res;

  if (binary())
    res= length_bytes == 1 ? HA_KEYTYPE_VARBINARY1 : HA_KEYTYPE_VARBINARY2;
  else
    res= length_bytes == 1 ? HA_KEYTYPE_VARTEXT1 : HA_KEYTYPE_VARTEXT2;
  return res;
}


/*
  Compressed columns need one extra byte to store the compression method.
  This byte is invisible to the end user, but not for the storage engine.
*/

void Field_varstring::sql_type(String &res) const
{
  THD *thd= table->in_use;
  CHARSET_INFO *cs=res.charset();
  size_t length;

  length= cs->cset->snprintf(cs,(char*) res.ptr(),
                             res.alloced_length(), "%s(%u)",
                              (has_charset() ? "varchar" : "varbinary"),
                              (uint) char_length());
  res.length(length);
  if ((thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40)) &&
      has_charset() && (charset()->state & MY_CS_BINSORT))
    res.append(STRING_WITH_LEN(" binary"));
}

/**
   For fields which are associated with character sets their length is provided
   in octets and their character set information is also provided as part of
   type information.

   @param   res       String which contains filed type and length.
*/
void Field_varstring::sql_rpl_type(String *res) const
{
  CHARSET_INFO *cs=charset();
  if (Field_varstring::has_charset())
  {
    size_t length= cs->cset->snprintf(cs, (char*) res->ptr(),
                                      res->alloced_length(),
                                      "varchar(%u octets) character set %s",
                                      field_length,
                                      charset()->cs_name.str);
    res->length(length);
  }
  else
    Field_varstring::sql_type(*res);
}


uint32 Field_varstring::data_length()
{
  return length_bytes == 1 ? (uint32) *ptr : uint2korr(ptr);
}

/*
  Functions to create a packed row.
  Here the number of length bytes are depending on the given max_length
*/

uchar *Field_varstring::pack(uchar *to, const uchar *from, uint max_length)
{
  uint length= length_bytes == 1 ? (uint) *from : uint2korr(from);
  set_if_smaller(max_length, field_length);
  if (length > max_length)
    length=max_length;

  /* Length always stored little-endian */
  *to++= length & 0xFF;
  if (max_length > 255)
    *to++= (length >> 8) & 0xFF;

  /* Store bytes of string */
  if (length > 0)
    memcpy(to, from+length_bytes, length);
  return to+length;
}


/**
   Unpack a varstring field from row data.

   This method is used to unpack a varstring field from a master
   whose size of the field is less than that of the slave.

   @note
   The string length is always packed little-endian.
  
   @param   to         Destination of the data
   @param   from       Source of the data
   @param   param_data Length bytes from the master's field data

   @return  New pointer into memory based on from + length of the data
*/
const uchar *
Field_varstring::unpack(uchar *to, const uchar *from, const uchar *from_end,
                        uint param_data)
{
  uint length;
  uint l_bytes= (param_data && (param_data < field_length)) ? 
                (param_data <= 255) ? 1 : 2 : length_bytes;

  if (from + l_bytes > from_end)
    return 0;                                 // Error in data

  if (l_bytes == 1)
  {
    to[0]= *from++;
    length= to[0];
    if (length_bytes == 2)
      to[1]= 0;
  }
  else /* l_bytes == 2 */
  {
    length= uint2korr(from);
    to[0]= *from++;
    to[1]= *from++;
  }
  if (length)
  {
    if (from + length > from_end || length > field_length)
      return 0;                                 // Error in data
    memcpy(to+ length_bytes, from, length);
  }
  return from+length;
}


uint Field_varstring::packed_col_length(const uchar *data_ptr, uint length)
{
  if (length > 255)
    return uint2korr(data_ptr)+2;
  return (uint) *data_ptr + 1;
}


uint Field_varstring::max_packed_col_length(uint max_length)
{
  return (max_length > 255 ? 2 : 1)+max_length;
}

void Field_varstring::val_str_from_ptr(String *val, const uchar *ptr) const
{
  val->set((const char*) get_data(ptr), get_length(ptr), field_charset());
}

uint Field_varstring::get_key_image(uchar *buff, uint length,
                                    const uchar *ptr_arg,
                                    imagetype type_arg) const
{
  String val;
  val_str_from_ptr(&val, ptr_arg);

  uint local_char_length= val.charpos(length / mbmaxlen());
  if (local_char_length < val.length())
    val.length(local_char_length);
  /* Key is always stored with 2 bytes */
  int2store(buff, val.length());
  memcpy(buff + HA_KEY_BLOB_LENGTH, val.ptr(), val.length());
  if (val.length() < length)
  {
    /*
      Must clear this as we do a memcmp in opt_range.cc to detect
      identical keys
    */
    memset(buff + HA_KEY_BLOB_LENGTH + val.length(), 0, length - val.length());
  }
  return HA_KEY_BLOB_LENGTH + val.length();
}


void Field_varstring::set_key_image(const uchar *buff,uint length)
{
  length= uint2korr(buff);			// Real length is here
  (void) store((const char*) buff + HA_KEY_BLOB_LENGTH, length, field_charset());
}


int Field_varstring::cmp_binary(const uchar *a_ptr, const uchar *b_ptr,
                                uint32 max_length) const
{
  uint32 a_length,b_length;

  if (length_bytes == 1)
  {
    a_length= (uint) *a_ptr;
    b_length= (uint) *b_ptr;
  }
  else
  {
    a_length= uint2korr(a_ptr);
    b_length= uint2korr(b_ptr);
  }
  set_if_smaller(a_length, max_length);
  set_if_smaller(b_length, max_length);
  if (a_length != b_length)
    return 1;
  return memcmp(a_ptr+length_bytes, b_ptr+length_bytes, a_length);
}


Field *Field_varstring::make_new_field(MEM_ROOT *root, TABLE *new_table,
                                       bool keep_type)
{
  Field_varstring *res= (Field_varstring*) Field::make_new_field(root,
                                                                 new_table,
                                                                 keep_type);
  if (res)
    res->length_bytes= length_bytes;
  return res;
}


Field *Field_varstring::new_key_field(MEM_ROOT *root, TABLE *new_table,
                                      uchar *new_ptr, uint32 length,
                                      uchar *new_null_ptr, uint new_null_bit)
{
  Field_varstring *res;
  if ((res= (Field_varstring*) Field::new_key_field(root, new_table,
                                                    new_ptr, length,
                                                    new_null_ptr, new_null_bit)))
  {
    /* Keys length prefixes are always packed with 2 bytes */
    res->length_bytes= 2;
  }
  return res;
}

bool Field_varstring::is_equal(const Column_definition &new_field) const
{
  return new_field.type_handler() == type_handler() &&
         new_field.length == field_length &&
         new_field.char_length == char_length() &&
         !new_field.compression_method() == !compression_method() &&
         new_field.charset == field_charset();
}


void Field_varstring::hash_not_null(Hasher *hasher)
{
  DBUG_ASSERT(marked_for_read());
  DBUG_ASSERT(!is_null());
  uint len=  length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
  hasher->add(charset(), ptr + length_bytes, len);
}


/**
  Compress field

  @param[out]    to         destination buffer for compressed data
  @param[in]     to_length  size of to
  @param[in]     from       data to compress
  @param[in]     length     from length
  @param[in]     max_length truncate `from' to this length
  @param[out]    out_length compessed data length
  @param[in]     cs         from character set
  @param[in]     nchars     copy no more than "nchars" characters

  In worst case (no compression performed) storage requirement is increased by
  1 byte to store header. If it exceeds field length, normal data truncation is
  performed.

  Generic compressed header format (1 byte):

  Bits 1-4: method specific bits
  Bits 5-8: compression method

  If compression method is 0 then header is immediately followed by
  uncompressed data.

  If compression method is zlib:

  Bits 1-3: number of bytes occupied by original data length
  Bits   4: true if zlib wrapper not present
  Bits 5-8: store 8 (zlib)

  Header is immediately followed by original data length,
  followed by compressed data.
*/

int Field_longstr::compress(char *to, uint to_length,
                            const char *from, uint length,
                            uint max_length,
                            uint *out_length,
                            CHARSET_INFO *cs, size_t nchars)
{
  THD *thd= get_thd();
  char *buf;
  uint buf_length;
  int rc= 0;

  if (String::needs_conversion_on_storage(length, cs, field_charset()) ||
      max_length < length)
  {
    set_if_smaller(max_length, static_cast<ulonglong>(mbmaxlen()) * length + 1);
    if (!(buf= (char*) my_malloc(PSI_INSTRUMENT_ME, max_length, MYF(MY_WME))))
    {
      *out_length= 0;
      return -1;
    }

    rc= well_formed_copy_with_check(buf, max_length, cs, from, length,
                                    nchars, true, &buf_length);
  }
  else
  {
    buf= const_cast<char*>(from);
    buf_length= length;
  }

  if (buf_length == 0)
    *out_length= 0;
  else if (buf_length >= thd->variables.column_compression_threshold &&
      (*out_length= compression_method()->compress(thd, to, buf, buf_length)))
    status_var_increment(thd->status_var.column_compressions);
  else
  {
    /* Store uncompressed */
    to[0]= 0;
    if (buf_length < to_length)
      memcpy(to + 1, buf, buf_length);
    else
    {
      /* Storing string at blob capacity, e.g. 255 bytes string to TINYBLOB. */
      rc= well_formed_copy_with_check(to + 1, to_length - 1, cs, from, length,
                                      nchars, true, &buf_length);
    }
    *out_length= buf_length + 1;
  }

  if (buf != from)
    my_free(buf);
  return rc;
}


/*
  Memory is allocated only when original data was actually compressed.
  Otherwise val_ptr points at data located immediately after header.

  Data can be stored uncompressed if data was shorter than threshold
  or compressed data was longer than original data.
*/

String *Field_longstr::uncompress(String *val_buffer, String *val_ptr,
                                  const uchar *from, uint from_length) const
{
  if (from_length)
  {
    uchar method= (*from & 0xF0) >> 4;

    /* Uncompressed data */
    if (!method)
    {
      val_ptr->set((const char*) from + 1, from_length - 1, field_charset());
      return val_ptr;
    }

    if (compression_methods[method].uncompress)
    {
      if (!compression_methods[method].uncompress(val_buffer, from, from_length,
                                                  field_length))
      {
        val_buffer->set_charset(field_charset());
        status_var_increment(get_thd()->status_var.column_decompressions);
        return val_buffer;
      }
    }
  }

  /*
    It would be better to return 0 in case of errors, but to take the
    safer route, let's return a zero string and let the general
    handler catch the error.
  */
  val_ptr->set("", 0, field_charset());
  return val_ptr;
}


int Field_varstring_compressed::store(const char *from, size_t length,
                                      CHARSET_INFO *cs)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  uint compressed_length;
  int rc= compress((char*) get_data(), field_length, from, (uint) length,
                   Field_varstring_compressed::max_display_length(),
                   &compressed_length, cs,
                   Field_varstring_compressed::char_length());
  store_length(compressed_length);
  return rc;
}

void Field_varstring_compressed::val_str_from_ptr(String *val, const uchar *ptr) const
{
  uncompress(val, val, get_data(ptr), get_length(ptr));
}


String *Field_varstring_compressed::val_str(String *val_buffer, String *val_ptr)
{
  DBUG_ASSERT(marked_for_read());
  return uncompress(val_buffer, val_ptr, get_data(), get_length());
}


double Field_varstring_compressed::val_real(void)
{
  DBUG_ASSERT(marked_for_read());
  THD *thd= get_thd();
  String buf;
  val_str(&buf, &buf);
  return Converter_strntod_with_warn(thd, Warn_filter(thd), field_charset(),
                                     buf.ptr(), buf.length()).result();
}


longlong Field_varstring_compressed::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  THD *thd= get_thd();
  String buf;
  val_str(&buf, &buf);
  return Converter_strntoll_with_warn(thd, Warn_filter(thd), field_charset(),
                                      buf.ptr(), buf.length()).result();
}


int Field_varstring_compressed::cmp(const uchar *a_ptr,
                                    const uchar *b_ptr) const
{
  String a, b;
  uint a_length, b_length;

  if (length_bytes == 1)
  {
    a_length= (uint) *a_ptr;
    b_length= (uint) *b_ptr;
  }
  else
  {
    a_length= uint2korr(a_ptr);
    b_length= uint2korr(b_ptr);
  }

  uncompress(&a, &a, a_ptr + length_bytes, a_length);
  uncompress(&b, &b, b_ptr + length_bytes, b_length);

  return sortcmp(&a, &b, field_charset());
}


Binlog_type_info Field_varstring_compressed::binlog_type_info() const
{
  return Binlog_type_info(Field_varstring_compressed::binlog_type(),
                          field_length, 2, charset());
}


/****************************************************************************
** blob type
** A blob is saved as a length and a pointer. The length is stored in the
** packlength slot and may be from 1-4.
****************************************************************************/

Field_blob::Field_blob(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg,
		       enum utype unireg_check_arg,
                       const LEX_CSTRING *field_name_arg,
                       TABLE_SHARE *share, uint blob_pack_length,
		       const DTCollation &collation)
  :Field_longstr(ptr_arg, BLOB_PACK_LENGTH_TO_MAX_LENGH(blob_pack_length),
                 null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg,
                 collation),
   packlength(blob_pack_length)
{
  DBUG_ASSERT(blob_pack_length <= 4); // Only pack lengths 1-4 supported currently
  flags|= BLOB_FLAG;
  share->blob_fields++;
  /* TODO: why do not fill table->s->blob_field array here? */
}


void Field_blob::store_length(uchar *i_ptr, uint i_packlength, uint32 i_number)
{
  store_lowendian(i_number, i_ptr, i_packlength);
}


uint32 Field_blob::get_length(const uchar *pos, uint packlength_arg) const
{
  return (uint32)read_lowendian(pos, packlength_arg);
}


/**
  Copy a value from another BLOB field of the same character set.
  This method is used by Copy_field, e.g. during ALTER TABLE.
*/
int Field_blob::copy_value(Field_blob *from)
{
  DBUG_ASSERT(field_charset() == from->charset());
  DBUG_ASSERT(!compression_method() == !from->compression_method());
  int rc= 0;
  uint32 length= from->get_length();
  uchar *data= from->get_ptr();
  if (packlength < from->packlength)
  {
    set_if_smaller(length, Field_blob::max_data_length());
    length= (uint32) Well_formed_prefix(field_charset(),
                                        (const char *) data, length).length();
    rc= report_if_important_data((const char *) data + length,
                                 (const char *) data + from->get_length(),
                                 true);
  }
  store_length(length);
  bmove(ptr + packlength, (uchar*) &data, sizeof(char*));
  return rc;
}


int Field_blob::store(const char *from,size_t length,CHARSET_INFO *cs)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  size_t copy_length, new_length;
  uint copy_len;
  char *tmp;
  char buff[STRING_BUFFER_USUAL_SIZE];
  String tmpstr(buff,sizeof(buff), &my_charset_bin);
  int rc;

  if (!length)
  {
    bzero(ptr,Field_blob::pack_length());
    return 0;
  }

  /*
    For min/max fields of statistical data 'table' is set to NULL.
    It could not be otherwise as this data is shared by many instances
    of the same base table.
  */

  if (table && table->blob_storage)    // GROUP_CONCAT with ORDER BY | DISTINCT
  {
    DBUG_ASSERT(!f_is_hex_escape(flags));
    DBUG_ASSERT(field_charset() == cs);
    DBUG_ASSERT(length <= max_data_length());
    
    new_length= length;
    copy_length= table->in_use->variables.group_concat_max_len;
    if (new_length > copy_length)
    {
      new_length= Well_formed_prefix(cs,
                                     from, copy_length, new_length).length();
      table->blob_storage->set_truncated_value(true);
    }
    if (!(tmp= table->blob_storage->store(from, new_length)))
      goto oom_error;

    Field_blob::store_length(new_length);
    bmove(ptr + packlength, (uchar*) &tmp, sizeof(char*));
    return 0;
  }

  /*
    If the 'from' address is in the range of the temporary 'value'-
    object we need to copy the content to a different location or it will be
    invalidated when the 'value'-object is reallocated to make room for
    the new character set.
  */
  if (from >= value.ptr() && from <= value.ptr()+value.length())
  {
    /*
      If content of the 'from'-address is cached in the 'value'-object
      it is possible that the content needs a character conversion.
    */
    if (!String::needs_conversion_on_storage(length, cs, field_charset()))
    {
      Field_blob::store_length(length);
      bmove(ptr + packlength, &from, sizeof(char*));
      return 0;
    }
    if (tmpstr.copy(from, length, cs))
      goto oom_error;
    from= tmpstr.ptr();
  }

  new_length= MY_MIN(max_data_length(), mbmaxlen() * length);
  if (value.alloc(new_length))
    goto oom_error;
  tmp= const_cast<char*>(value.ptr());

  if (f_is_hex_escape(flags))
  {
    copy_length= my_copy_with_hex_escaping(field_charset(),
                                           tmp, new_length,
                                           from, length);
    Field_blob::store_length(copy_length);
    bmove(ptr + packlength, (uchar*) &tmp, sizeof(char*));
    return 0;
  }
  rc= well_formed_copy_with_check((char*) value.ptr(), (uint) new_length,
                                  cs, from, length,
                                  length, true, &copy_len);
  value.length(copy_len);
  Field_blob::store_length(copy_len);
  bmove(ptr+packlength,(uchar*) &tmp,sizeof(char*));

  return rc;

oom_error:
  /* Fatal OOM error */
  bzero(ptr,Field_blob::pack_length());
  return -1; 
}


void Field_blob::hash_not_null(Hasher *hasher)
{
  DBUG_ASSERT(marked_for_read());
  DBUG_ASSERT(!is_null());
  char *blob;
  memcpy(&blob, ptr + packlength, sizeof(char*));
  if (blob)
    hasher->add(Field_blob::charset(), blob, get_length(ptr));
}


double Field_blob::val_real(void)
{
  DBUG_ASSERT(marked_for_read());
  char *blob;
  memcpy(&blob, ptr+packlength, sizeof(char*));
  if (!blob)
    return 0.0;
  THD *thd= get_thd();
  return  Converter_strntod_with_warn(thd, Warn_filter(thd),
                                      Field_blob::charset(),
                                      blob, get_length(ptr)).result();
}


longlong Field_blob::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  char *blob;
  memcpy(&blob, ptr+packlength, sizeof(char*));
  if (!blob)
    return 0;
  THD *thd= get_thd();
  return Converter_strntoll_with_warn(thd, Warn_filter(thd),
                                      Field_blob::charset(),
                                      blob, get_length(ptr)).result();
}


String *Field_blob::val_str(String *val_buffer __attribute__((unused)),
			    String *val_ptr)
{
  DBUG_ASSERT(marked_for_read());
  char *blob;
  memcpy(&blob, ptr+packlength, sizeof(char*));
  if (!blob)
    val_ptr->set("",0,charset());	// A bit safer than ->length(0)
  else
    val_ptr->set((const char*) blob,get_length(ptr),charset());
  return val_ptr;
}


my_decimal *Field_blob::val_decimal(my_decimal *decimal_value)
{
  DBUG_ASSERT(marked_for_read());
  const char *blob;
  size_t length;
  memcpy(&blob, ptr+packlength, sizeof(const uchar*));
  if (!blob)
  {
    blob= "";
    length= 0;
  }
  else
    length= get_length(ptr);

  THD *thd= get_thd();
  Converter_str2my_decimal_with_warn(thd, Warn_filter(thd),
                                     E_DEC_FATAL_ERROR & ~E_DEC_BAD_NUM,
                                     Field_blob::charset(),
                                     blob, length, decimal_value);
  return decimal_value;
}


int Field_blob::cmp(const uchar *a,uint32 a_length, const uchar *b,
		    uint32 b_length) const
{
  return field_charset()->strnncollsp(a, a_length, b, b_length);
}


int Field_blob::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  uchar *blob1,*blob2;
  memcpy(&blob1, a_ptr+packlength, sizeof(char*));
  memcpy(&blob2, b_ptr+packlength, sizeof(char*));
  size_t a_len= get_length(a_ptr), b_len= get_length(b_ptr);
  return cmp(blob1, (uint32)a_len, blob2, (uint32)b_len);
}


int Field_blob::cmp_prefix(const uchar *a_ptr, const uchar *b_ptr,
                           size_t prefix_len) const
{
  uchar *blob1,*blob2;
  memcpy(&blob1, a_ptr+packlength, sizeof(char*));
  memcpy(&blob2, b_ptr+packlength, sizeof(char*));
  size_t a_len= get_length(a_ptr), b_len= get_length(b_ptr);
  return field_charset()->coll->strnncollsp_nchars(field_charset(),
                                                   blob1, a_len,
                                                   blob2, b_len,
                                                   prefix_len /
                                                   field_charset()->mbmaxlen);
}


int Field_blob::cmp_binary(const uchar *a_ptr, const uchar *b_ptr,
			   uint32 max_length) const
{
  char *a,*b;
  uint diff;
  uint32 a_length,b_length;
  memcpy(&a, a_ptr+packlength, sizeof(char*));
  memcpy(&b, b_ptr+packlength, sizeof(char*));
  a_length=get_length(a_ptr);
  if (a_length > max_length)
    a_length=max_length;
  b_length=get_length(b_ptr);
  if (b_length > max_length)
    b_length=max_length;
  if (uint32 len= MY_MIN(a_length,b_length))
    diff= memcmp(a,b,len);
  else
    diff= 0;
  return diff ? diff : (int) (a_length - b_length);
}


/* The following is used only when comparing a key */

uint Field_blob::get_key_image_itRAW(const uchar *ptr_arg, uchar *buff,
                                     uint length) const
{
  size_t blob_length= get_length(ptr_arg);
  const uchar *blob= get_ptr(ptr_arg);
  size_t local_char_length= length / mbmaxlen();
  local_char_length= field_charset()->charpos(blob, blob + blob_length,
                                              local_char_length);
  set_if_smaller(blob_length, local_char_length);

  if (length > blob_length)
  {
    /*
      Must clear this as we do a memcmp in opt_range.cc to detect
      identical keys
    */
    bzero(buff+HA_KEY_BLOB_LENGTH+blob_length, (length-blob_length));
    length=(uint) blob_length;
  }
  int2store(buff,length);
  if (length)
    memcpy(buff+HA_KEY_BLOB_LENGTH, blob, length);
  return HA_KEY_BLOB_LENGTH+length;
}


void Field_blob::set_key_image(const uchar *buff,uint length)
{
  length= uint2korr(buff);
  (void) Field_blob::store((const char*) buff+HA_KEY_BLOB_LENGTH, length,
                           field_charset());
}


int Field_blob::key_cmp(const uchar *key_ptr, uint max_key_length) const
{
  uchar *blob1;
  size_t blob_length=get_length(ptr);
  memcpy(&blob1, ptr+packlength, sizeof(char*));
  CHARSET_INFO *cs= charset();
  size_t local_char_length= max_key_length / cs->mbmaxlen;
  local_char_length= cs->charpos(blob1, blob1+blob_length,
                                 local_char_length);
  set_if_smaller(blob_length, local_char_length);
  return Field_blob::cmp(blob1, (uint32)blob_length,
			 key_ptr+HA_KEY_BLOB_LENGTH,
			 uint2korr(key_ptr));
}

int Field_blob::key_cmp(const uchar *a,const uchar *b) const
{
  return Field_blob::cmp(a+HA_KEY_BLOB_LENGTH, uint2korr(a),
			 b+HA_KEY_BLOB_LENGTH, uint2korr(b));
}


Field *Field_blob::new_key_field(MEM_ROOT *root, TABLE *new_table,
                                 uchar *new_ptr, uint32 length,
                                 uchar *new_null_ptr, uint new_null_bit)
{
  Field_varstring *res= new (root) Field_varstring(new_ptr, length, 2,
                                                   new_null_ptr,
                                                   new_null_bit, Field::NONE,
                                                   &field_name,
                                                   table->s, charset());
  res->init(new_table);
  return res;
}


/**
   Save the field metadata for blob fields.

   Saves the pack length in the first byte of the field metadata array
   at index of *metadata_ptr.

   @param   metadata_ptr   First byte of field metadata

   @returns number of bytes written to metadata_ptr
*/
Binlog_type_info Field_blob::binlog_type_info() const
{
  DBUG_ASSERT(Field_blob::type() == binlog_type());
  return Binlog_type_info(Field_blob::type(), pack_length_no_ptr(), 1,
                          charset());
}


uint32 Field_blob::sort_length() const
{
  return packlength == 4 ?
    UINT_MAX32 :
    (uint32) field_length + sort_suffix_length();
}


uint32 Field_blob::sort_suffix_length() const
{
  return field_charset() == &my_charset_bin ?  packlength : 0;
}


void Field_blob::sort_string(uchar *to,uint length)
{
  String buf;

  val_str(&buf, &buf);
  if (!buf.length() && field_charset()->pad_char == 0)
    bzero(to,length);
  else
  {
    if (field_charset() == &my_charset_bin)
    {
      /*
        Store length of blob last in blob to shorter blobs before longer blobs
      */
      length-= packlength;
      store_bigendian(buf.length(), to + length, packlength);
    }

#ifdef DBUG_ASSERT_EXISTS
    size_t rc=
#endif
    field_charset()->strnxfrm(to, length, length,
                              (const uchar *) buf.ptr(), buf.length(),
                              MY_STRXFRM_PAD_WITH_SPACE |
                              MY_STRXFRM_PAD_TO_MAXLEN);
    DBUG_ASSERT(rc == length);
  }
}


/*
  Return the data type handler, according to packlength.
  Implemented in field.cc rather than in field.h
  to avoid exporting type_handler_xxx with MYSQL_PLUGIN_IMPORT.
*/
const Type_handler *Field_blob::type_handler() const
{
  /*
    This is a temporary solution and will be fixed soon (in 10.9?).
    Type_handler_*blob_json will provide its own Field_blob_json
    and Field_blob_compressed_json.
  */
  if (Type_handler_json_common::has_json_valid_constraint(this))
    return Type_handler_json_common::
             json_blob_type_handler_by_length_bytes(packlength);

  switch (packlength) {
  case 1: return &type_handler_tiny_blob;
  case 2: return &type_handler_blob;
  case 3: return &type_handler_medium_blob;
  }
  return &type_handler_long_blob;
}


void Field_blob::sql_type(String &res) const
{
  const char *str;
  uint length;
  switch (packlength) {
  default: str="tiny"; length=4; break;
  case 2:  str="";     length=0; break;
  case 3:  str="medium"; length= 6; break;
  case 4:  str="long";  length=4; break;
  }
  res.set_ascii(str,length);
  if (charset() == &my_charset_bin)
  {
    res.append(STRING_WITH_LEN("blob"));
    if (packlength == 2 && (get_thd()->variables.sql_mode & MODE_ORACLE))
      res.append(STRING_WITH_LEN("(65535)"));
  }
  else
  {
    res.append(STRING_WITH_LEN("text"));
  }
}

uchar *Field_blob::pack(uchar *to, const uchar *from, uint max_length)
{
  uint32 length=get_length(from, packlength);			// Length of from string

  /*
    Store max length, which will occupy packlength bytes. If the max
    length given is smaller than the actual length of the blob, we
    just store the initial bytes of the blob.
  */
  store_length(to, packlength, MY_MIN(length, max_length));

  /*
    Store the actual blob data, which will occupy 'length' bytes.
   */
  if (length > 0)
  {
    from= get_ptr(from);
    memcpy(to+packlength, from,length);
  }
  return to+packlength+length;
}


/**
   Unpack a blob field from row data.

   This method is used to unpack a blob field from a master whose size of 
   the field is less than that of the slave. Note: This method is included
   to satisfy inheritance rules, but is not needed for blob fields. It
   simply is used as a pass-through to the original unpack() method for
   blob fields.

   @param   to         Destination of the data
   @param   from       Source of the data
   @param   param_data @c TRUE if base types should be stored in little-
                       endian format, @c FALSE if native format should
                       be used.

   @return  New pointer into memory based on from + length of the data
*/

const uchar *Field_blob::unpack(uchar *to, const uchar *from,
                                const uchar *from_end, uint param_data)
{
  DBUG_ENTER("Field_blob::unpack");
  DBUG_PRINT("enter", ("to: %p; from: %p; param_data: %u",
                       to, from, param_data));
  uint const master_packlength=
    param_data > 0 ? param_data & 0xFF : packlength;
  if (from + master_packlength > from_end)
    DBUG_RETURN(0);                             // Error in data
  uint32 const length= get_length(from, master_packlength);
  DBUG_DUMP("packed", from, length + master_packlength);
  if (from + master_packlength + length > from_end)
    DBUG_RETURN(0);
  set_ptr(length, const_cast<uchar*> (from) + master_packlength);
  DBUG_RETURN(from + master_packlength + length);
}


uint Field_blob::packed_col_length(const uchar *data_ptr, uint length)
{
  if (length > 255)
    return uint2korr(data_ptr)+2;
  return (uint) *data_ptr + 1;
}


uint Field_blob::max_packed_col_length(uint max_length)
{
  return (max_length > 255 ? 2 : 1)+max_length;
}


/*
  Blob fields are regarded equal if they have same character set,
  same blob store length and if either both are compressed or both are
  uncompressed.
  The logic for compression is that we don't have to uncompress and compress
  again an already compressed field just because compression method changes.
*/

bool Field_blob::is_equal(const Column_definition &new_field) const
{
  return new_field.type_handler() == type_handler() &&
         !new_field.compression_method() == !compression_method() &&
         new_field.pack_length == pack_length() &&
         new_field.charset == field_charset();
}


void Field_blob::make_send_field(Send_field *field)
{
  /*
    Historically all BLOB variant Fields are displayed as MYSQL_TYPE_BLOB
    in the result set metadata. Note, Item can work differently and
    display the exact BLOB type, such as
    MYSQL_TYPE_{TINY_BLOB|BLOB|MEDIUM_BLOB|LONG_BLOB}.
    QQ: this should be made consistent eventually.
  */
  Field_longstr::make_send_field(field);
  field->set_handler(&type_handler_blob);
}


bool Field_blob::make_empty_rec_store_default_value(THD *thd, Item *item)
{
  DBUG_ASSERT(flags & BLOB_FLAG);
  int res= item->save_in_field(this, true);
  DBUG_ASSERT(res != 3); // Field_blob never returns 3
  if (res)
    return true; // E.g. truncation happened
  reset(); // Clear the pointer to a String, it should not be written to frm
  return false;
}


int Field_blob_compressed::store(const char *from, size_t length,
                                 CHARSET_INFO *cs)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  uint compressed_length;
  uint max_length= max_data_length();
  uint to_length= (uint) MY_MIN(max_length, mbmaxlen() * length + 1);
  String tmp(from, length, cs);
  int rc;

  if (from >= value.ptr() && from <= value.end() && tmp.copy(from, length, cs))
    goto oom;

  if (value.alloc(to_length))
    goto oom;

  rc= compress((char*) value.ptr(), to_length, tmp.ptr(), (uint) length,
               max_length, &compressed_length, cs, (uint) length);
  set_ptr(compressed_length, (uchar*) value.ptr());
  return rc;

oom:
  set_ptr((uint32) 0, NULL);
  return -1;
}


String *Field_blob_compressed::val_str(String *val_buffer, String *val_ptr)
{
  DBUG_ASSERT(marked_for_read());
  return uncompress(val_buffer, val_ptr, get_ptr(), get_length());
}


double Field_blob_compressed::val_real(void)
{
  DBUG_ASSERT(marked_for_read());
  THD *thd= get_thd();
  String buf;
  val_str(&buf, &buf);
  return Converter_strntod_with_warn(thd, Warn_filter(thd), field_charset(),
                                     buf.ptr(), buf.length()).result();
}


longlong Field_blob_compressed::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  THD *thd= get_thd();
  String buf;
  val_str(&buf, &buf);
  return Converter_strntoll_with_warn(thd, Warn_filter(thd), field_charset(),
                                      buf.ptr(), buf.length()).result();
}

Binlog_type_info Field_blob_compressed::binlog_type_info() const
{
  return Binlog_type_info(Field_blob_compressed::binlog_type(),
                          pack_length_no_ptr(), 1, charset());
}

/****************************************************************************
** enum type.
** This is a string which only can have a selection of different values.
** If one uses this string in a number context one gets the type number.
****************************************************************************/

sql_mode_t Field_enum::can_handle_sql_mode_dependency_on_store() const
{
  return MODE_PAD_CHAR_TO_FULL_LENGTH;
}


enum ha_base_keytype Field_enum::key_type() const
{
  switch (packlength) {
  default: return HA_KEYTYPE_BINARY;
  case 2: return HA_KEYTYPE_USHORT_INT;
  case 3: return HA_KEYTYPE_UINT24;
  case 4: return HA_KEYTYPE_ULONG_INT;
  case 8: return HA_KEYTYPE_ULONGLONG;
  }
}

void Field_enum::store_type(ulonglong value)
{
  store_lowendian(value, ptr, packlength);
}


/**
  @note
    Storing a empty string in a enum field gives a warning
    (if there isn't a empty value in the enum)
*/

int Field_enum::store(const char *from,size_t length,CHARSET_INFO *cs)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int err= 0;
  char buff[STRING_BUFFER_USUAL_SIZE];
  String tmpstr(buff,sizeof(buff), &my_charset_bin);

  /* Convert character set if necessary */
  if (String::needs_conversion_on_storage(length, cs, field_charset()))
  { 
    uint dummy_errors;
    tmpstr.copy(from, length, cs, field_charset(), &dummy_errors);
    from= tmpstr.ptr();
    length=  tmpstr.length();
  }

  /* Remove end space */
  length= (uint) field_charset()->lengthsp(from, length);
  uint tmp=find_type2(typelib, from, length, field_charset());
  if (!tmp)
  {
    if (length < 6) // Can't be more than 99999 enums
    {
      /* This is for reading numbers with LOAD DATA INFILE */
      char *end;
      tmp=(uint) cs->strntoul(from,length,10,&end,&err);
      if (err || end != from+length || tmp > typelib->count)
      {
	tmp=0;
	set_warning(WARN_DATA_TRUNCATED, 1);
	err= 1;
      }
      if ((get_thd()->count_cuted_fields <= CHECK_FIELD_EXPRESSION) && !length)
        err= 0;
    }
    else
    {
      set_warning(WARN_DATA_TRUNCATED, 1);
      err= 1;
    }
  }
  store_type((ulonglong) tmp);
  return err;
}


int Field_enum::store(double nr)
{
  return Field_enum::store((longlong) nr, FALSE);
}


int Field_enum::store(longlong nr, bool unsigned_val)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int error= 0;
  if ((ulonglong) nr > typelib->count || nr == 0)
  {
    set_warning(WARN_DATA_TRUNCATED, 1);
    if (nr != 0 || get_thd()->count_cuted_fields > CHECK_FIELD_EXPRESSION)
    {
      nr= 0;
      error= 1;
    }
  }
  store_type((ulonglong) (uint) nr);
  return error;
}


double Field_enum::val_real(void)
{
  return (double) Field_enum::val_int();
}


longlong Field_enum::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  return val_int(ptr);
}

longlong Field_enum::val_int(const uchar *real_ptr) const
{
  return read_lowendian(real_ptr, packlength);
}

/**
   Save the field metadata for enum fields.

   Saves the real type in the first byte and the pack length in the 
   second byte of the field metadata array at index of *metadata_ptr and
   *(metadata_ptr + 1).

   @param   metadata_ptr   First byte of field metadata

   @returns number of bytes written to metadata_ptr
*/
Binlog_type_info Field_enum::binlog_type_info() const
{
  DBUG_ASSERT(Field_enum::type() == binlog_type());
  return Binlog_type_info(Field_enum::type(), real_type() + (pack_length() << 8),
                          2, charset(), (TYPELIB *)get_typelib(), NULL);
}


String *Field_enum::val_str(String *val_buffer __attribute__((unused)),
			    String *val_ptr)
{
  uint tmp=(uint) Field_enum::val_int();
  if (!tmp || tmp > typelib->count)
    val_ptr->set("", 0, field_charset());
  else
    val_ptr->set((const char*) typelib->type_names[tmp-1],
		 typelib->type_lengths[tmp-1],
		 field_charset());
  return val_ptr;
}

int Field_enum::cmp(const uchar *a_ptr, const uchar *b_ptr) const
{
  ulonglong a=Field_enum::val_int(a_ptr);
  ulonglong b=Field_enum::val_int(b_ptr);
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

void Field_enum::sort_string(uchar *to,uint length __attribute__((unused)))
{
  ulonglong value=Field_enum::val_int();
  to+=packlength-1;
  for (uint i=0 ; i < packlength ; i++)
  {
    *to-- = (uchar) (value & 255);
    value>>=8;
  }
}


void Field_enum::sql_type(String &res) const
{
  char buffer[255];
  String enum_item(buffer, sizeof(buffer), res.charset());

  res.length(0);
  res.append(STRING_WITH_LEN("enum("));

  bool flag=0;
  uint *len= typelib->type_lengths;
  for (const char **pos= typelib->type_names; *pos; pos++, len++)
  {
    uint dummy_errors;
    if (flag)
      res.append(',');
    /* convert to res.charset() == utf8, then quote */
    enum_item.copy(*pos, *len, charset(), res.charset(), &dummy_errors);
    append_unescaped(&res, enum_item.ptr(), enum_item.length());
    flag= 1;
  }
  res.append(')');
}


Field *Field_enum::make_new_field(MEM_ROOT *root, TABLE *new_table,
                                  bool keep_type)
{
  Field_enum *res= (Field_enum*) Field::make_new_field(root, new_table,
                                                       keep_type);
  if (res)
    res->typelib= copy_typelib(root, typelib);
  return res;
}


/*
   set type.
   This is a string which can have a collection of different values.
   Each string value is separated with a ','.
   For example "One,two,five"
   If one uses this string in a number context one gets the bits as a longlong
   number.
*/


int Field_set::store(const char *from,size_t length,CHARSET_INFO *cs)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  bool got_warning= 0;
  int err= 0;
  char *not_used;
  uint not_used2;
  char buff[STRING_BUFFER_USUAL_SIZE];
  String tmpstr(buff,sizeof(buff), &my_charset_bin);

  /* Convert character set if necessary */
  if (String::needs_conversion_on_storage(length, cs, field_charset()))
  { 
    uint dummy_errors;
    tmpstr.copy(from, length, cs, field_charset(), &dummy_errors);
    from= tmpstr.ptr();
    length=  tmpstr.length();
  }
  ulonglong tmp= find_set(typelib, from, length, field_charset(),
                          &not_used, &not_used2, &got_warning);
  if (!tmp && length && length < 22)
  {
    /* This is for reading numbers with LOAD DATA INFILE */
    char *end;
    tmp= cs->strntoull(from,length,10,&end,&err);
    if (err || end != from+length ||
	tmp > (ulonglong) (((longlong) 1 << typelib->count) - (longlong) 1))
    {
      tmp=0;      
      set_warning(WARN_DATA_TRUNCATED, 1);
      err= 1;
    }
  }
  else if (got_warning)
    set_warning(WARN_DATA_TRUNCATED, 1);
  store_type(tmp);
  return err;
}


int Field_set::store(longlong nr, bool unsigned_val)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int error= 0;
  ulonglong max_nr;

  if (sizeof(ulonglong)*8 <= typelib->count)
    max_nr= ULONGLONG_MAX;
  else
    max_nr= (1ULL << typelib->count) - 1;

  if ((ulonglong) nr > max_nr)
  {
    nr&= max_nr;
    set_warning(WARN_DATA_TRUNCATED, 1);
    error=1;
  }
  store_type((ulonglong) nr);
  return error;
}


String *Field_set::val_str(String *val_buffer,
			   String *val_ptr __attribute__((unused)))
{
  ulonglong tmp=(ulonglong) Field_enum::val_int();
  uint bitnr=0;

  val_buffer->set_charset(field_charset());
  val_buffer->length(0);

  while (tmp && bitnr < (uint) typelib->count)
  {
    if (tmp & 1)
    {
      if (val_buffer->length())
	val_buffer->append(&field_separator, 1, &my_charset_latin1);
      String str(typelib->type_names[bitnr], typelib->type_lengths[bitnr],
		 field_charset());
      val_buffer->append(str);
    }
    tmp>>=1;
    bitnr++;
  }
  return val_buffer;
}


void Field_set::sql_type(String &res) const
{
  char buffer[255];
  String set_item(buffer, sizeof(buffer), res.charset());

  res.length(0);
  res.append(STRING_WITH_LEN("set("));

  bool flag=0;
  uint *len= typelib->type_lengths;
  for (const char **pos= typelib->type_names; *pos; pos++, len++)
  {
    uint dummy_errors;
    if (flag)
      res.append(',');
    /* convert to res.charset() == utf8, then quote */
    set_item.copy(*pos, *len, charset(), res.charset(), &dummy_errors);
    append_unescaped(&res, set_item.ptr(), set_item.length());
    flag= 1;
  }
  res.append(')');
}

Binlog_type_info Field_set::binlog_type_info() const
{
  DBUG_ASSERT(Field_set::type() == binlog_type());
  return Binlog_type_info(Field_set::type(), real_type()
           + (pack_length() << 8), 2, charset(), NULL, (TYPELIB *)get_typelib());
}

/**
  @retval
    1  if the fields are equally defined
  @retval
    0  if the fields are unequally defined
*/

bool Field::eq_def(const Field *field) const
{
  if (real_type() != field->real_type() || charset() != field->charset() ||
      pack_length() != field->pack_length())
    return 0;
  return 1;
}


/**
  Compare the first t1::count type names.

  @return TRUE if the type names of t1 match those of t2. FALSE otherwise.
*/

static bool compare_type_names(CHARSET_INFO *charset, const TYPELIB *t1,
                                                      const TYPELIB *t2)
{
  for (uint i= 0; i < t1->count; i++)
    if (charset->strnncoll(t1->type_names[i], t1->type_lengths[i],
                           t2->type_names[i], t2->type_lengths[i]))
      return FALSE;
  return TRUE;
}

/**
  @return
  returns 1 if the fields are equally defined
*/

bool Field_enum::eq_def(const Field *field) const
{
  const TYPELIB *values;

  if (!Field::eq_def(field))
    return FALSE;

  values= ((Field_enum*) field)->typelib;

  /* Definition must be strictly equal. */
  if (typelib->count != values->count)
    return FALSE;

  return compare_type_names(field_charset(), typelib, values);
}


/**
  Check whether two fields can be considered 'equal' for table
  alteration purposes. Fields are equal if they retain the same
  pack length and if new members are added to the end of the list.

  @return true if fields are compatible.
          false otherwise.
*/

bool Field_enum::is_equal(const Column_definition &new_field) const
{
  const TYPELIB *values= new_field.interval;

  /*
    The fields are compatible if they have the same flags,
    type, charset and have the same underlying length.
  */
  if (new_field.type_handler() != type_handler() ||
      new_field.charset != field_charset() ||
      new_field.pack_length != pack_length())
    return false;

  /*
    Changing the definition of an ENUM or SET column by adding a new
    enumeration or set members to the end of the list of valid member
    values only alters table metadata and not table data.
  */
  if (typelib->count > values->count)
    return false;

  /* Check whether there are modification before the end. */
  if (! compare_type_names(field_charset(), typelib, new_field.interval))
    return false;

  return true;
}


uchar *Field_enum::pack(uchar *to, const uchar *from, uint max_length)
{
  DBUG_ENTER("Field_enum::pack");
  DBUG_PRINT("debug", ("packlength: %d", packlength));
  DBUG_DUMP("from", from, packlength);
  DBUG_RETURN(pack_int(to, from, packlength));
}

const uchar *Field_enum::unpack(uchar *to, const uchar *from, 
                                const uchar *from_end, uint param_data)
{
  DBUG_ENTER("Field_enum::unpack");
  DBUG_PRINT("debug", ("packlength: %d", packlength));
  DBUG_DUMP("from", from, packlength);
  DBUG_RETURN(unpack_int(to, from, from_end, packlength));
}


/**
  @return
  returns 1 if the fields are equally defined
*/
bool Field_num::eq_def(const Field *field) const
{
  if (!Field::eq_def(field))
    return 0;
  Field_num *from_num= (Field_num*) field;

  if (unsigned_flag != from_num->unsigned_flag ||
      (zerofill && !from_num->zerofill && !zero_pack()) ||
      dec != from_num->dec)
    return 0;
  return 1;
}


/**
  Check whether two numeric fields can be considered 'equal' for table
  alteration purposes. Fields are equal if they are of the same type
  and retain the same pack length.
*/

bool Field_num::is_equal(const Column_definition &new_field) const
{
  if (((new_field.flags & UNSIGNED_FLAG) != (flags & UNSIGNED_FLAG)) ||
      ((new_field.flags & AUTO_INCREMENT_FLAG) > (flags & AUTO_INCREMENT_FLAG)))
    return false;

  const Type_handler *th= type_handler(), *new_th = new_field.type_handler();

  if (th == new_th && new_field.pack_length == pack_length())
    return true;
  /* FIXME: Test and consider returning true for the following:
  TINYINT UNSIGNED to BIT(8)
  SMALLINT UNSIGNED to BIT(16)
  MEDIUMINT UNSIGNED to BIT(24)
  INT UNSIGNED to BIT(32)
  BIGINT UNSIGNED to BIT(64)

  BIT(1..7) to TINYINT, or BIT(1..8) to TINYINT UNSIGNED
  BIT(9..15) to SMALLINT, or BIT(9..16) to SMALLINT UNSIGNED
  BIT(17..23) to MEDIUMINT, or BIT(17..24) to MEDIUMINT UNSIGNED
  BIT(25..31) to INT, or BIT(25..32) to INT UNSIGNED
  BIT(57..63) to BIGINT, or BIT(57..64) to BIGINT UNSIGNED

  Note: InnoDB stores integers in big-endian format, and BIT appears
  to use big-endian format. For storage engines that use little-endian
  format for integers, we can only return true for the TINYINT
  conversion. */

  return false;
}


bool Field_enum::can_optimize_range_or_keypart_ref(const Item_bool_func *cond,
                                                   const Item *item) const
{
  switch (item->cmp_type())
  {
  case TIME_RESULT:
    return false;
  case INT_RESULT:
  case DECIMAL_RESULT:
  case REAL_RESULT:
    return true;
  case STRING_RESULT:
    return charset() == cond->compare_collation();
  case ROW_RESULT:
    DBUG_ASSERT(0);
    break;
  }
  return false;
}


/*
  Bit field.

  We store the first 0 - 6 uneven bits among the null bits 
  at the start of the record. The rest bytes are stored in 
  the record itself.

  For example:

  CREATE TABLE t1 (a int, b bit(17), c bit(21) not null, d bit(8));
  We would store data  as follows in the record:

  Byte        Bit
  1           7 - reserve for delete
              6 - null bit for 'a'
              5 - null bit for 'b'
              4 - first (high) bit of 'b'
              3 - first (high) bit of 'c'
              2 - second bit of 'c'
              1 - third bit of 'c'
              0 - forth bit of 'c'
  2           7 - firth bit of 'c'
              6 - null bit for 'd'
  3 - 6       four bytes for 'a'
  7 - 8       two bytes for 'b'
  9 - 10      two bytes for 'c'
  11          one byte for 'd'
*/

Field_bit::Field_bit(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
                     uchar null_bit_arg, uchar *bit_ptr_arg, uchar bit_ofs_arg,
                     enum utype unireg_check_arg,
                     const LEX_CSTRING *field_name_arg)
  : Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
          unireg_check_arg, field_name_arg),
    bit_ptr(bit_ptr_arg), bit_ofs(bit_ofs_arg), bit_len(len_arg & 7),
    bytes_in_rec(len_arg / 8)
{
  DBUG_ENTER("Field_bit::Field_bit");
  DBUG_PRINT("enter", ("ptr_arg: %p, null_ptr_arg: %p, len_arg: %u, bit_len: %u, bytes_in_rec: %u",
                       ptr_arg, null_ptr_arg, len_arg, bit_len, bytes_in_rec));
  flags|= UNSIGNED_FLAG;
  /*
    Ensure that Field::eq() can distinguish between two different bit fields.
    (two bit fields that are not null, may have same ptr and null_ptr)
  */
  if (!null_ptr_arg)
    null_bit= bit_ofs_arg;
  DBUG_VOID_RETURN;
}


const DTCollation & Field_bit::dtcollation() const
{
  static DTCollation tmp(&my_charset_bin,
                         DERIVATION_IMPLICIT, MY_REPERTOIRE_UNICODE30);
  return tmp;
}


/*
  This method always calculates hash over 8 bytes.
  This is different from how the HEAP engine calculate hash:
  HEAP takes into account the actual octet size, so say for BIT(18)
  it calculates hash over three bytes only:
  - the incomplete byte with bits 16..17
  - the two full bytes with bits 0..15
  See hp_rec_hashnr(), hp_hashnr() for details.

  The HEAP way is more efficient, especially for short lengths.
  Let's consider fixing Field_bit eventually to do it in the HEAP way,
  with proper measures to upgrade partitioned tables easy.
*/
void Field_bit::hash_not_null(Hasher *hasher)
{
  DBUG_ASSERT(marked_for_read());
  DBUG_ASSERT(!is_null());
  longlong value= Field_bit::val_int();
  uchar tmp[8];
  mi_int8store(tmp,value);
  hasher->add(&my_charset_bin, tmp, 8);
}


size_t
Field_bit::do_last_null_byte() const
{
  /*
    Code elsewhere is assuming that bytes are 8 bits, so I'm using
    that value instead of the correct one: CHAR_BIT.

    REFACTOR SUGGESTION (Matz): Change to use the correct number of
    bits. On systems with CHAR_BIT > 8 (not very common), the storage
    will lose the extra bits.
  */
  DBUG_PRINT("test", ("bit_ofs: %d, bit_len: %d  bit_ptr: %p",
                      bit_ofs, bit_len, bit_ptr));
  uchar *result;
  if (bit_len == 0)
    result= null_ptr;
  else if (bit_ofs + bit_len > 8)
    result= bit_ptr + 1;
  else
    result= bit_ptr;

  if (result)
    return (size_t) (result - table->record[0]) + 1;
  return LAST_NULL_BYTE_UNDEF;
}


Field *Field_bit::new_key_field(MEM_ROOT *root, TABLE *new_table,
                                uchar *new_ptr, uint32 length, 
                                uchar *new_null_ptr, uint new_null_bit)
{
  Field_bit *res;
  if ((res= (Field_bit*) Field::new_key_field(root, new_table, new_ptr, length,
                                              new_null_ptr, new_null_bit)))
  {
    /* Move bits normally stored in null_pointer to new_ptr */
    res->bit_ptr= new_ptr;
    res->bit_ofs= 0;
    if (bit_len)
      res->ptr++;                               // Store rest of data here
  }
  return res;
}


bool Field_bit::is_equal(const Column_definition &new_field) const
{
  return new_field.type_handler() == type_handler() &&
         new_field.length == max_display_length();
}

                       
int Field_bit::store(const char *from, size_t length, CHARSET_INFO *cs)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int delta;

  for (; length && !*from; from++, length--)          // skip left 0's
    ;
  delta= (int)(bytes_in_rec - length);

  if (delta < -1 ||
      (delta == -1 && (uchar) *from > ((1 << bit_len) - 1)) ||
      (!bit_len && delta < 0))
  {
    set_rec_bits((1 << bit_len) - 1, bit_ptr, bit_ofs, bit_len);
    memset(ptr, 0xff, bytes_in_rec);
    if (get_thd()->really_abort_on_warning())
      set_warning(ER_DATA_TOO_LONG, 1);
    else
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
    return 1;
  }
  /* delta is >= -1 here */
  if (delta > 0)
  {
    if (bit_len)
      clr_rec_bits(bit_ptr, bit_ofs, bit_len);
    bzero(ptr, delta);
    memcpy(ptr + delta, from, length);
  }
  else if (delta == 0)
  {
    if (bit_len)
      clr_rec_bits(bit_ptr, bit_ofs, bit_len);
    memcpy(ptr, from, length);
  }
  else
  {
    if (bit_len)
    {
      set_rec_bits((uchar) *from, bit_ptr, bit_ofs, bit_len);
      from++;
    }
    memcpy(ptr, from, bytes_in_rec);
  }
  return 0;
}


int Field_bit::store(double nr)
{
  return Field_bit::store((longlong) nr, FALSE);
}


int Field_bit::store(longlong nr, bool unsigned_val)
{
  char buf[8];

  mi_int8store(buf, nr);
  return store(buf, 8, NULL);
}


int Field_bit::store_decimal(const my_decimal *val)
{
  int err= 0;
  longlong i= convert_decimal2longlong(val, 1, &err);
  return MY_TEST(err | store(i, TRUE));
}


double Field_bit::val_real(void)
{
  return (double) Field_bit::val_int();
}


longlong Field_bit::val_int(void)
{
  DBUG_ASSERT(marked_for_read());
  ulonglong bits= 0;
  if (bit_len)
  {
    bits= get_rec_bits(bit_ptr, bit_ofs, bit_len);
    bits<<= (bytes_in_rec * 8);
  }

  switch (bytes_in_rec) {
  case 0: return bits;
  case 1: return bits | (ulonglong) ptr[0];
  case 2: return bits | mi_uint2korr(ptr);
  case 3: return bits | mi_uint3korr(ptr);
  case 4: return bits | mi_uint4korr(ptr);
  case 5: return bits | mi_uint5korr(ptr);
  case 6: return bits | mi_uint6korr(ptr);
  case 7: return bits | mi_uint7korr(ptr);
  default: return mi_uint8korr(ptr + bytes_in_rec - sizeof(longlong));
  }
}  


String *Field_bit::val_str(String *val_buffer,
                           String *val_ptr __attribute__((unused)))
{
  DBUG_ASSERT(marked_for_read());
  char buff[sizeof(longlong)];
  uint length= MY_MIN(pack_length(), sizeof(longlong));
  ulonglong bits= val_int();
  mi_int8store(buff,bits);

  val_buffer->alloc(length);
  memcpy((char *) val_buffer->ptr(), buff+8-length, length);
  val_buffer->length(length);
  val_buffer->set_charset(&my_charset_bin);
  return val_buffer;
}


my_decimal *Field_bit::val_decimal(my_decimal *deciaml_value)
{
  DBUG_ASSERT(marked_for_read());
  int2my_decimal(E_DEC_FATAL_ERROR, val_int(), 1, deciaml_value);
  return deciaml_value;
}


/*
  Compare two bit fields using pointers within the record.
  SYNOPSIS
    cmp_max()
    a                 Pointer to field->ptr in first record
    b                 Pointer to field->ptr in second record
    max_len           Maximum length used in index
  DESCRIPTION
    This method is used from key_rec_cmp used by merge sorts used
    by partitioned index read and later other similar places.
    The a and b pointer must be pointers to the field in a record
    (not the table->record[0] necessarily)
*/
int Field_bit::cmp_prefix(const uchar *a, const uchar *b,
                          size_t prefix_len) const
{
  my_ptrdiff_t a_diff= a - ptr;
  my_ptrdiff_t b_diff= b - ptr;
  if (bit_len)
  {
    int flag;
    uchar bits_a= get_rec_bits(bit_ptr+a_diff, bit_ofs, bit_len);
    uchar bits_b= get_rec_bits(bit_ptr+b_diff, bit_ofs, bit_len);
    if ((flag= (int) (bits_a - bits_b)))
      return flag;
  }
  if (!bytes_in_rec)
    return 0;
  return memcmp(a, b, bytes_in_rec);
}


int Field_bit::key_cmp(const uchar *str, uint) const
{
  if (bit_len)
  {
    int flag;
    uchar bits= get_rec_bits(bit_ptr, bit_ofs, bit_len);
    if ((flag= (int) (bits - *str)))
      return flag;
    str++;
  }
  return memcmp(ptr, str, bytes_in_rec);
}


int Field_bit::cmp_offset(my_ptrdiff_t row_offset)
{
  if (bit_len)
  {
    int flag;
    uchar bits_a= get_rec_bits(bit_ptr, bit_ofs, bit_len);
    uchar bits_b= get_rec_bits(bit_ptr + row_offset, bit_ofs, bit_len);
    if ((flag= (int) (bits_a - bits_b)))
      return flag;
  }
  return memcmp(ptr, ptr + row_offset, bytes_in_rec);
}


uint Field_bit::get_key_image(uchar *buff, uint length, const uchar *ptr_arg, imagetype type_arg) const
{
  if (bit_len)
  {
    const uchar *bit_ptr_for_arg= ptr_arg + (bit_ptr - ptr);
    uchar bits= get_rec_bits(bit_ptr_for_arg, bit_ofs, bit_len);
    *buff++= bits;
    length--;
  }
  uint tmp_data_length = MY_MIN(length, bytes_in_rec);
  memcpy(buff, ptr, tmp_data_length);
  return tmp_data_length + 1;
}


/**
   Returns the number of bytes field uses in row-based replication 
   row packed size.

   This method is used in row-based replication to determine the number
   of bytes that the field consumes in the row record format. This is
   used to skip fields in the master that do not exist on the slave.

   @param   field_metadata   Encoded size in field metadata

   @returns The size of the field based on the field metadata.
*/
uint Field_bit::pack_length_from_metadata(uint field_metadata) const
{
  uint const from_len= (field_metadata >> 8U) & 0x00ff;
  uint const from_bit_len= field_metadata & 0x00ff;
  uint const source_size= from_len + ((from_bit_len > 0) ? 1 : 0);
  return (source_size);
}


bool
Field_bit::compatible_field_size(uint field_metadata,
                                 const Relay_log_info * __attribute__((unused)),
                                 uint16 mflags,
                                 int *order_var) const
{
  DBUG_ENTER("Field_bit::compatible_field_size");
  DBUG_ASSERT((field_metadata >> 16) == 0);
  uint from_bit_len=
    8 * (field_metadata >> 8) + (field_metadata & 0xff);
  uint to_bit_len= max_display_length();
  DBUG_PRINT("debug", ("from_bit_len: %u, to_bit_len: %u",
                       from_bit_len, to_bit_len));
  /*
    If the bit length exact flag is clear, we are dealing with an old
    master, so we allow some less strict behaviour if replicating by
    moving both bit lengths to an even multiple of 8.

    We do this by computing the number of bytes to store the field
    instead, and then compare the result.
   */
  if (!(mflags & Table_map_log_event::TM_BIT_LEN_EXACT_F)) {
    from_bit_len= (from_bit_len + 7) / 8;
    to_bit_len= (to_bit_len + 7) / 8;
  }

  *order_var= compare(from_bit_len, to_bit_len);
  DBUG_RETURN(TRUE);
}



void Field_bit::sql_type(String &res) const
{
  CHARSET_INFO *cs= res.charset();
  size_t length= cs->cset->snprintf(cs, (char*) res.ptr(), res.alloced_length(),
                                   "bit(%d)", (int) field_length);
  res.length(length);
}


uchar *
Field_bit::pack(uchar *to, const uchar *from, uint max_length)
{
  DBUG_ASSERT(max_length > 0);
  uint length;
  if (bit_len > 0)
  {
    /*
      We have the following:

      ptr        Points into a field in record R1
      from       Points to a field in a record R2
      bit_ptr    Points to the byte (in the null bytes) that holds the
                 odd bits of R1
      from_bitp  Points to the byte that holds the odd bits of R2

      We have the following:

          ptr - bit_ptr = from - from_bitp

      We want to isolate 'from_bitp', so this gives:

          ptr - bit_ptr - from = - from_bitp
          - ptr + bit_ptr + from = from_bitp
          bit_ptr + from - ptr = from_bitp
     */
    uchar bits= get_rec_bits(bit_ptr + (from - ptr), bit_ofs, bit_len);
    *to++= bits;
  }
  length= MY_MIN(bytes_in_rec, max_length - (bit_len > 0));
  memcpy(to, from, length);
  return to + length;
}


/**
   Unpack a bit field from row data.

   This method is used to unpack a bit field from a master whose size
   of the field is less than that of the slave.

   @param   to         Destination of the data
   @param   from       Source of the data
   @param   param_data Bit length (upper) and length (lower) values

   @return  New pointer into memory based on from + length of the data
*/
const uchar *
Field_bit::unpack(uchar *to, const uchar *from, const uchar *from_end,
                  uint param_data)
{
  DBUG_ENTER("Field_bit::unpack");
  DBUG_PRINT("enter", ("to: %p, from: %p, param_data: 0x%x",
                       to, from, param_data));
  DBUG_PRINT("debug", ("bit_ptr: %p, bit_len: %u, bit_ofs: %u",
                       bit_ptr, bit_len, bit_ofs));
  uint const from_len= (param_data >> 8U) & 0x00ff;
  uint const from_bit_len= param_data & 0x00ff;
  DBUG_PRINT("debug", ("from_len: %u, from_bit_len: %u",
                       from_len, from_bit_len));
  /*
    If the parameter data is zero (i.e., undefined), or if the master
    and slave have the same sizes, then use the old unpack() method.
  */
  if (param_data == 0 ||
      ((from_bit_len == bit_len) && (from_len == bytes_in_rec)))
  {
    if (from + bytes_in_rec + MY_TEST(bit_len) > from_end)
      return 0;                                 // Error in data

    if (bit_len > 0)
    {
      /*
        set_rec_bits is a macro, don't put the post-increment in the
        argument since that might cause strange side-effects.

        For the choice of the second argument, see the explanation for
        Field_bit::pack().
      */
      set_rec_bits(*from, bit_ptr + (to - ptr), bit_ofs, bit_len);
      from++;
    }
    memcpy(to, from, bytes_in_rec);
    DBUG_RETURN(from + bytes_in_rec);
  }

  /*
    We are converting a smaller bit field to a larger one here.
    To do that, we first need to construct a raw value for the original
    bit value stored in the from buffer. Then that needs to be converted
    to the larger field then sent to store() for writing to the field.
    Lastly the odd bits need to be masked out if the bytes_in_rec > 0.
    Otherwise stray bits can cause spurious values.
  */

  uint len= from_len + ((from_bit_len > 0) ? 1 : 0);
  uint new_len= (field_length + 7) / 8;

  if (from + len > from_end || new_len < len)
    return 0;                                 // Error in data

  char *value= (char *)my_alloca(new_len);
  bzero(value, new_len);

  memcpy(value + (new_len - len), from, len);
  /*
    Mask out the unused bits in the partial byte. 
    TODO: Add code to the master to always mask these bits and remove
          the following.
  */
  if ((from_bit_len > 0) && (from_len > 0))
    value[new_len - len]= value[new_len - len] & ((1U << from_bit_len) - 1);
  bitmap_set_bit(table->write_set,field_index);
  store(value, new_len, system_charset_info);
  my_afree(value);
  DBUG_RETURN(from + len);
}


int Field_bit::set_default()
{
  if (bit_len > 0)
  {
    my_ptrdiff_t const col_offset= table->s->default_values - table->record[0];
    uchar bits= get_rec_bits(bit_ptr + col_offset, bit_ofs, bit_len);
    set_rec_bits(bits, bit_ptr, bit_ofs, bit_len);
  }
  return Field::set_default();
}

/*
  Bit field support for non-MyISAM tables.
*/

Field_bit_as_char::Field_bit_as_char(uchar *ptr_arg, uint32 len_arg,
                                     uchar *null_ptr_arg, uchar null_bit_arg,
                                     enum utype unireg_check_arg,
                                     const LEX_CSTRING *field_name_arg)
  :Field_bit(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, 0, 0,
             unireg_check_arg, field_name_arg)
{
  flags|= UNSIGNED_FLAG;
  bit_len= 0;
  bytes_in_rec= (len_arg + 7) / 8;
}


int Field_bit_as_char::store(const char *from, size_t length, CHARSET_INFO *cs)
{
  DBUG_ASSERT(marked_for_write_or_computed());
  int delta;
  uchar bits= (uchar) (field_length & 7);

  for (; length && !*from; from++, length--)          // skip left 0's
    ;
  delta= (int)(bytes_in_rec - length);

  if (delta < 0 ||
      (delta == 0 && bits && (uint) (uchar) *from >= (uint) (1 << bits)))
  {
    memset(ptr, 0xff, bytes_in_rec);
    if (bits)
      *ptr&= ((1 << bits) - 1); /* set first uchar */
    if (get_thd()->really_abort_on_warning())
      set_warning(ER_DATA_TOO_LONG, 1);
    else
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
    return 1;
  }
  bzero(ptr, delta);
  memcpy(ptr + delta, from, length);
  return 0;
}


void Field_bit_as_char::sql_type(String &res) const
{
  CHARSET_INFO *cs= res.charset();
  size_t length= cs->cset->snprintf(cs, (char*) res.ptr(), res.alloced_length(),
                                   "bit(%d)", (int) field_length);
  res.length(length);
}


/*****************************************************************************
  Handling of field and Create_field
*****************************************************************************/

bool Column_definition::create_interval_from_interval_list(MEM_ROOT *mem_root,
                                               bool reuse_interval_list_values)
{
  DBUG_ENTER("Column_definition::create_interval_from_interval_list");
  DBUG_ASSERT(!interval);
  TYPELIB *tmpint;
  if (!(interval= tmpint= (TYPELIB*) alloc_root(mem_root, sizeof(TYPELIB))))
    DBUG_RETURN(true); // EOM

  List_iterator<String> it(interval_list);
  StringBuffer<64> conv;
  char comma_buf[5]; /* 5 bytes for 'filename' charset */
  DBUG_ASSERT(sizeof(comma_buf) >= charset->mbmaxlen);
  int comma_length= charset->wc_mb(',',
                                   (uchar*) comma_buf,
                                   (uchar*) comma_buf + sizeof(comma_buf));
  DBUG_ASSERT(comma_length >= 0 && comma_length <= (int) sizeof(comma_buf));

  if (!multi_alloc_root(mem_root,
                        &tmpint->type_names,
                        sizeof(char*) * (interval_list.elements + 1),
                        &tmpint->type_lengths,
                        sizeof(uint) * (interval_list.elements + 1),
                        NullS))
    goto err; // EOM

  tmpint->name= "";
  tmpint->count= interval_list.elements;

  for (uint i= 0; i < interval_list.elements; i++)
  {
    uint32 dummy;
    String *tmp= it++;
    LEX_CSTRING value;
    if (String::needs_conversion(tmp->length(), tmp->charset(),
                                 charset, &dummy))
    {
      uint cnv_errs;
      conv.copy(tmp->ptr(), tmp->length(), tmp->charset(), charset, &cnv_errs);
      value.str= strmake_root(mem_root, conv.ptr(), conv.length());
      value.length= conv.length();
    }
    else
    {
      value.str= reuse_interval_list_values ? tmp->ptr() :
                                              strmake_root(mem_root,
                                                           tmp->ptr(),
                                                           tmp->length());
      value.length= tmp->length();
    }
    if (!value.str)
      goto err; // EOM

    // Strip trailing spaces.
    value.length= charset->lengthsp(value.str, value.length);
    ((char*) value.str)[value.length]= '\0';

    if (real_field_type() == MYSQL_TYPE_SET)
    {
      if (charset->instr(value.str, value.length,
                         comma_buf, comma_length, NULL, 0))
      {
        ErrConvString err(tmp);
        my_error(ER_ILLEGAL_VALUE_FOR_TYPE, MYF(0), "set", err.ptr());
        goto err;
      }
    }
    tmpint->type_names[i]= value.str;
    tmpint->type_lengths[i]= (uint)value.length;
  }
  tmpint->type_names[interval_list.elements]= 0;    // End marker
  tmpint->type_lengths[interval_list.elements]= 0;
  interval_list.empty();  // Don't need interval_list anymore
  DBUG_RETURN(false);
err:
  interval= NULL;  // Avoid having both non-empty interval_list and interval
  DBUG_RETURN(true);
}


bool Column_definition::prepare_interval_field(MEM_ROOT *mem_root,
                                               bool reuse_interval_list_values)
{
  DBUG_ENTER("Column_definition::prepare_interval_field");
  DBUG_ASSERT(real_field_type() == MYSQL_TYPE_ENUM ||
              real_field_type() == MYSQL_TYPE_SET);
  /*
    Interval values are either in "interval" or in "interval_list",
    but not in both at the same time, and are not empty at the same time.
    - Values are in "interval_list" when we're coming from the parser
      in CREATE TABLE or in CREATE {FUNCTION|PROCEDURE}.
    - Values are in "interval" when we're in ALTER TABLE.

    In a corner case with an empty set like SET(''):
    - after the parser we have interval_list.elements==1
    - in ALTER TABLE we have a non-NULL interval with interval->count==1,
      with interval->type_names[0]=="" and interval->type_lengths[0]==0.
    So the assert is still valid for this corner case.

    ENUM and SET with no values at all (e.g. ENUM(), SET()) are not possible,
    as the parser requires at least one element, so for a ENUM or SET field it
    should never happen that both internal_list.elements and interval are 0.
  */
  DBUG_ASSERT((interval == NULL) == (interval_list.elements > 0));

  /*
    Create typelib from interval_list, and if necessary
    convert strings from client character set to the
    column character set.
  */
  if (interval_list.elements &&
      create_interval_from_interval_list(mem_root,
                                         reuse_interval_list_values))
    DBUG_RETURN(true);

  if (!reuse_interval_list_values)
  {
    /*
      We're initializing from an existing table or view Field_enum
      (e.g. for a %TYPE variable) rather than from the parser.
      The constructor Column_definition(THD*,Field*,Field*) has already
      copied the TYPELIB pointer from the original Field_enum.
      Now we need to make a permanent copy of that TYPELIB,
      as the original field can be freed before the end of the life
      cycle of "this".
    */
    DBUG_ASSERT(interval);
    if (!(interval= copy_typelib(mem_root, interval)))
      DBUG_RETURN(true);
  }
  prepare_interval_field_calc_length();
  DBUG_RETURN(false);
}


bool Column_definition::set_attributes(THD *thd,
                                       const Lex_field_type_st &def,
                                       column_definition_type_t type)
{
  DBUG_ASSERT(type_handler() == &type_handler_null);
  DBUG_ASSERT(length == 0);
  DBUG_ASSERT(decimals == 0);

  set_handler(def.type_handler());
  return type_handler()->Column_definition_set_attributes(thd, this,
                                                          def, type);
}


void
Column_definition_attributes::set_length_and_dec(const Lex_length_and_dec_st
                                                 &type)
{
  if (type.has_explicit_length())
    length= type.length_overflowed() ? (ulonglong) UINT_MAX32 + 1 :
                                       (ulonglong) type.length();

  if (type.has_explicit_dec())
    decimals= type.dec();
}


void Column_definition::create_length_to_internal_length_bit()
{
  if (f_bit_as_char(pack_flag))
  {
    pack_length= ((length + 7) & ~7) / 8;
  }
  else
  {
    pack_length= (uint) length / 8;
  }
}


void Column_definition::create_length_to_internal_length_newdecimal()
{
  DBUG_ASSERT(length < UINT_MAX32);
  decimal_digit_t prec= get_decimal_precision((uint)length, decimals,
                                              flags & UNSIGNED_FLAG);
  pack_length= my_decimal_get_binary_size(prec, decimals);
}


bool check_expression(Virtual_column_info *vcol, const LEX_CSTRING *name,
                      enum_vcol_info_type type, Alter_info *alter_info)

{
  bool ret;
  Item::vcol_func_processor_result res;
  res.alter_info= alter_info;

  if (!vcol->name.length)
    vcol->name= *name;

  /*
    Walk through the Item tree checking if all items are valid
    to be part of the virtual column
  */
  ret= vcol->expr->walk(&Item::check_vcol_func_processor, 0, &res);
  vcol->flags= res.errors;

  uint filter= VCOL_IMPOSSIBLE;
  if (type != VCOL_GENERATED_VIRTUAL && type != VCOL_DEFAULT)
    filter|= VCOL_NOT_STRICTLY_DETERMINISTIC;
  if (type != VCOL_DEFAULT)
    filter|= VCOL_NEXTVAL;

  if (unlikely(ret || (res.errors & filter)))
  {
    my_error(ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED, MYF(0), res.name,
             vcol_type_name(type), name->str);
    return TRUE;
  }
  /*
    Safe to call before fix_fields as long as vcol's don't include sub
    queries (which is now checked in check_vcol_func_processor)
  */
  if (vcol->expr->check_cols(1))
    return TRUE;
  return FALSE;
}


bool Column_definition::check_length(uint mysql_errno, uint limit) const
{
  if (length <= limit)
    return false;
  my_error(mysql_errno, MYF(0), field_name.str, static_cast<ulong>(limit));
  return true;
}


bool Column_definition::fix_attributes_int(uint default_length)
{
  if (length)
    return check_length(ER_TOO_BIG_DISPLAYWIDTH, MAX_FIELD_CHARLENGTH);
  length= default_length;
  return false;
}


bool Column_definition::fix_attributes_real(uint default_length)
{
  /* change FLOAT(precision) to FLOAT or DOUBLE */
  if (!length && !decimals)
  {
    length= default_length;
    decimals= NOT_FIXED_DEC;
  }
  if (length < decimals && decimals != NOT_FIXED_DEC)
  {
    my_error(ER_M_BIGGER_THAN_D, MYF(0), field_name.str);
    return true;
  }
  if (decimals != NOT_FIXED_DEC && decimals >= FLOATING_POINT_DECIMALS)
  {
    my_error(ER_TOO_BIG_SCALE, MYF(0),
             field_name.str, static_cast<uint>(FLOATING_POINT_DECIMALS-1));
    return true;
  }
  return check_length(ER_TOO_BIG_DISPLAYWIDTH, MAX_FIELD_CHARLENGTH);
}


bool Column_definition::fix_attributes_decimal()
{
  if (decimals >= NOT_FIXED_DEC)
  {
    my_error(ER_TOO_BIG_SCALE, MYF(0),
             field_name.str, static_cast<uint>(NOT_FIXED_DEC - 1));
    return true;
  }
  my_decimal_trim(&length, &decimals);
  if (length > DECIMAL_MAX_PRECISION)
  {
    my_error(ER_TOO_BIG_PRECISION, MYF(0), field_name.str,
             DECIMAL_MAX_PRECISION);
    return true;
  }
  if (length < decimals)
  {
    my_error(ER_M_BIGGER_THAN_D, MYF(0), field_name.str);
    return true;
  }
  length= my_decimal_precision_to_length((uint) length, decimals,
                                         flags & UNSIGNED_FLAG);
  pack_length= my_decimal_get_binary_size((uint) length, decimals);
  return false;
}


bool Column_definition::fix_attributes_bit()
{
  if (!length)
    length= 1;
  pack_length= ((uint) length + 7) / 8;
  return check_length(ER_TOO_BIG_DISPLAYWIDTH, MAX_BIT_FIELD_LENGTH);
}


bool Column_definition::fix_attributes_temporal_with_time(uint int_part_length)
{
  if (length > MAX_DATETIME_PRECISION)
  {
    my_error(ER_TOO_BIG_PRECISION, MYF(0), field_name.str,
             MAX_DATETIME_PRECISION);
    return true;
  }
  decimals= (uint) length;
  length+= int_part_length + (length ? 1 : 0);
  return false;
}


bool Column_definition::validate_check_constraint(THD *thd)
{
  return check_constraint &&
         check_expression(check_constraint, &field_name, VCOL_CHECK_FIELD);
}


bool Column_definition::check(THD *thd)
{
  DBUG_ENTER("Column_definition::check");

  /* Initialize data for a computed field */
  if (vcol_info)
  {
    DBUG_ASSERT(vcol_info->expr);
    vcol_info->set_handler(type_handler());
    if (check_expression(vcol_info, &field_name, vcol_info->stored_in_db
                         ? VCOL_GENERATED_STORED : VCOL_GENERATED_VIRTUAL))
      DBUG_RETURN(TRUE);
  }

  if (type_handler()->Column_definition_validate_check_constraint(thd, this))
    DBUG_RETURN(TRUE);

  if (default_value)
  {
    Item *def_expr= default_value->expr;
    if (check_expression(default_value, &field_name, VCOL_DEFAULT))
      DBUG_RETURN(TRUE);

    /* Constant's are stored in the 'empty_record', except for blobs */
    if (def_expr->basic_const_item())
    {
      if (def_expr->type() == Item::NULL_ITEM)
      {
        default_value= 0;
        if ((flags & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) == NOT_NULL_FLAG)
        {
          my_error(ER_INVALID_DEFAULT, MYF(0), field_name.str);
          DBUG_RETURN(1);
        }
      }
    }
  }

  if (default_value && (flags & AUTO_INCREMENT_FLAG))
  {
    my_error(ER_INVALID_DEFAULT, MYF(0), field_name.str);
    DBUG_RETURN(1);
  }

  if (default_value && !default_value->expr->basic_const_item() &&
      mysql_timestamp_type() == MYSQL_TIMESTAMP_DATETIME &&
      default_value->expr->type() == Item::FUNC_ITEM)
  {
    /*
      Special case: NOW() for TIMESTAMP and DATETIME fields are handled
      as in MariaDB 10.1 by marking them in unireg_check.
    */
    Item_func *fn= static_cast<Item_func*>(default_value->expr);
    if (fn->functype() == Item_func::NOW_FUNC &&
        (fn->decimals == 0 || fn->decimals >= length))
    {
      default_value= 0;
      unireg_check= Field::TIMESTAMP_DN_FIELD;
    }
  }

  if (on_update)
  {
    if (mysql_timestamp_type() != MYSQL_TIMESTAMP_DATETIME ||
        on_update->decimals < length)
    {
      my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name.str);
      DBUG_RETURN(TRUE);
    }
    unireg_check= unireg_check == Field::NONE ? Field::TIMESTAMP_UN_FIELD
                                              : Field::TIMESTAMP_DNUN_FIELD;
  }
  else if (flags & AUTO_INCREMENT_FLAG)
    unireg_check= Field::NEXT_NUMBER;

  if (type_handler()->Column_definition_fix_attributes(this))
    DBUG_RETURN(true);

  /* Remember the value of length */
  char_length= (uint)length;

  /*
    Set NO_DEFAULT_VALUE_FLAG if this field doesn't have a default value and
    it is NOT NULL, not an AUTO_INCREMENT field.
    We need to do this check here and in mysql_create_prepare_table() as
    sp_head::fill_field_definition() calls this function.
  */
  if (!default_value && unireg_check == Field::NONE && (flags & NOT_NULL_FLAG))
  {
    /*
      TIMESTAMP columns get implicit DEFAULT value when
      explicit_defaults_for_timestamp is not set.
    */
    if (((thd->variables.option_bits & OPTION_EXPLICIT_DEF_TIMESTAMP) ||
        !is_timestamp_type()) && !vers_sys_field())
    {
      flags|= NO_DEFAULT_VALUE_FLAG;
    }
  }


  if ((flags & AUTO_INCREMENT_FLAG) &&
      !type_handler()->type_can_have_auto_increment_attribute())
  {
    my_error(ER_WRONG_FIELD_SPEC, MYF(0), field_name.str);
    DBUG_RETURN(TRUE);
  }

  DBUG_RETURN(FALSE); /* success */
}

enum_field_types get_blob_type_from_length(ulong length)
{
  enum_field_types type;
  if (length < 256)
    type= MYSQL_TYPE_TINY_BLOB;
  else if (length < 65536)
    type= MYSQL_TYPE_BLOB;
  else if (length < 256L*256L*256L)
    type= MYSQL_TYPE_MEDIUM_BLOB;
  else
    type= MYSQL_TYPE_LONG_BLOB;
  return type;
}


uint pack_length_to_packflag(uint type)
{
  switch (type) {
    case 1: return f_settype((uint) MYSQL_TYPE_TINY);
    case 2: return f_settype((uint) MYSQL_TYPE_SHORT);
    case 3: return f_settype((uint) MYSQL_TYPE_INT24);
    case 4: return f_settype((uint) MYSQL_TYPE_LONG);
    case 8: return f_settype((uint) MYSQL_TYPE_LONGLONG);
  }
  return 0;					// This shouldn't happen
}


uint Column_definition_attributes::pack_flag_to_pack_length() const
{
  uint type= f_packtype(pack_flag); // 0..15
  DBUG_ASSERT(type < 16);
  switch (type) {
  case MYSQL_TYPE_TINY:     return 1;
  case MYSQL_TYPE_SHORT:    return 2;
  case MYSQL_TYPE_LONG:     return 4;
  case MYSQL_TYPE_LONGLONG: return 8;
  case MYSQL_TYPE_INT24:    return 3;
  }
  return 0; // This should not happen
}


Field *Column_definition_attributes::make_field(TABLE_SHARE *share,
                                                MEM_ROOT *mem_root,
                                                const Record_addr *rec,
                                                const Type_handler *handler,
                                                const LEX_CSTRING *field_name,
                                                uint32 flags)
                                                const
{
  DBUG_ASSERT(length <= UINT_MAX32);
  DBUG_PRINT("debug", ("field_type: %s, field_length: %u, interval: %p, pack_flag: %s%s%s%s%s",
                       handler->name().ptr(), (uint) length, interval,
                       FLAGSTR(pack_flag, FIELDFLAG_BINARY),
                       FLAGSTR(pack_flag, FIELDFLAG_INTERVAL),
                       FLAGSTR(pack_flag, FIELDFLAG_NUMBER),
                       FLAGSTR(pack_flag, FIELDFLAG_PACK),
                       FLAGSTR(pack_flag, FIELDFLAG_BLOB)));

  Record_addr addr(rec->ptr(), f_maybe_null(pack_flag) ? rec->null() :
                                                         Bit_addr());
  /*
    Special code for the BIT-alike data types
    who store data bits together with NULL-bits.
  */
  Bit_addr bit(rec->null());
  if (f_maybe_null(pack_flag))
    bit.inc();
  return handler->make_table_field_from_def(share, mem_root, field_name,
                                            addr, bit, this, flags);
}


bool Field_vers_trx_id::test_if_equality_guarantees_uniqueness(const Item* item) const
{
  return item->is_of_type(Item::CONST_ITEM, TIME_RESULT);
}


Column_definition_attributes::Column_definition_attributes(const Field *field)
 :length(field->character_octet_length() / field->charset()->mbmaxlen),
  interval(NULL),
  charset(field->charset()), // May be NULL ptr
  srid(0),
  pack_flag(0),
  decimals(field->decimals()),
  unireg_check(field->unireg_check)
{}


Column_definition_attributes::
  Column_definition_attributes(const Type_all_attributes &attr)
 :length(attr.max_length),
  interval(attr.get_typelib()),
  charset(attr.collation.collation),
  srid(0),
  pack_flag(attr.unsigned_flag ? 0 : FIELDFLAG_DECIMAL),
  decimals(attr.decimals),
  unireg_check(Field::NONE)
{}


/** Create a field suitable for create of table. */

Column_definition::Column_definition(THD *thd, Field *old_field,
                                               Field *orig_field)
 :Column_definition_attributes(old_field)
{
  srid= 0;
  on_update=  NULL;
  field_name= old_field->field_name;
  flags=      old_field->flags;
  pack_length=old_field->pack_length();
  set_handler(old_field->type_handler());
  comment=    old_field->comment;
  vcol_info=  old_field->vcol_info;
  option_list= old_field->option_list;
  explicitly_nullable= !(old_field->flags & NOT_NULL_FLAG);
  compression_method_ptr= 0;
  versioning= VERSIONING_NOT_SET;
  invisible= old_field->invisible;
  interval_list.empty(); // prepare_interval_field() needs this
  char_length= (uint) length;

  if (orig_field)
  {
    default_value= orig_field->default_value;
    check_constraint= orig_field->check_constraint;
    if (orig_field->unireg_check == Field::TMYSQL_COMPRESSED)
    {
      unireg_check= Field::TMYSQL_COMPRESSED;
      compression_method_ptr= zlib_compression_method;
    }
  }
  else
  {
    default_value= 0;
    check_constraint= 0;
  }

  type_handler()->Column_definition_reuse_fix_attributes(thd, this, old_field);

  /*
    Copy the default (constant/function) from the column object orig_field, if
    supplied. We do this if all these conditions are met:

    - The column allows a default.

    - The column type is not a BLOB type (as BLOB's doesn't have constant
      defaults)

    - The original column (old_field) was properly initialized with a record
      buffer pointer.

    - The column didn't have a default expression
  */
  if (!(flags & (NO_DEFAULT_VALUE_FLAG | BLOB_FLAG)) &&
      old_field->ptr != NULL && orig_field != NULL)
  {
    if (orig_field->unireg_check != Field::NEXT_NUMBER)
      unireg_check= orig_field->unireg_check;

    /* Get the value from default_values */
    const uchar *dv= orig_field->table->s->default_values;
    if (!default_value && !orig_field->is_null_in_record(dv))
    {
      StringBuffer<MAX_FIELD_WIDTH> tmp(charset);
      String *res= orig_field->val_str(&tmp, orig_field->ptr_in_record(dv));
      char *pos= (char*) thd->strmake(res->ptr(), res->length());
      default_value= new (thd->mem_root) Virtual_column_info();
      default_value->expr=
        new (thd->mem_root) Item_string(thd, pos, res->length(), charset);
      default_value->utf8= 0;
    }
  }
}


/**
  The common part for data type redefinition:
    CREATE TABLE t1 (a INT) AS SELECT a FROM t2;
  See Type_handler::Column_definition_redefine_stage1()
  for data type specific code.

  @param this         - The field definition corresponding to the expression
                        in the "AS SELECT.." part.

  @param dup_field    - The field definition from the "CREATE TABLE (...)" part.
                        It has already underwent prepare_stage1(), so
                        must be fully initialized:
                        -- dup_field->charset is set and BINARY
                           sorting style is applied, see find_bin_collation().

  @param file         - The table handler
*/
void
Column_definition::redefine_stage1_common(const Column_definition *dup_field,
                                          const handler *file)
{
  set_handler(dup_field->type_handler());
  default_value= dup_field->default_value;
  DBUG_ASSERT(dup_field->charset); // Set by prepare_stage1()
  charset=      dup_field->charset;
  length=       dup_field->char_length;
  pack_length=  dup_field->pack_length;
  decimals=     dup_field->decimals;
  unireg_check= dup_field->unireg_check;
  flags=        dup_field->flags;
  interval=     dup_field->interval;
  vcol_info=    dup_field->vcol_info;
  invisible=    dup_field->invisible;
  check_constraint= dup_field->check_constraint;
  comment=      dup_field->comment;
  option_list=  dup_field->option_list;
  versioning=   dup_field->versioning;
}



/**
  maximum possible character length for blob.
  
  This method is used in Item_field::set_field to calculate
  max_length for Item.
  
  For example:
    CREATE TABLE t2 SELECT CONCAT(tinyblob_utf8_column) FROM t1;
  must create a "VARCHAR(255) CHARACTER SET utf8" column.
  
  @return
    length
*/

uint32 Field_blob::char_length() const
{
  return Field_blob::character_octet_length();
}


uint32 Field_blob::character_octet_length() const
{
  switch (packlength)
  {
  case 1:
    return 255;
  case 2:
    return 65535;
  case 3:
    return 16777215;
  case 4:
    return (uint32) UINT_MAX32;
  default:
    DBUG_ASSERT(0); // we should never go here
    return 0;
  }
}


/**
  Makes a clone of this object for ALTER/CREATE TABLE

  @param mem_root        MEM_ROOT where to clone the field
*/

Create_field *Create_field::clone(MEM_ROOT *mem_root) const
{
  Create_field *res= new (mem_root) Create_field(*this);
  return res;
}

/**
   Return true if default is an expression that must be saved explicitly

   This is:
     - Not basic constants
     - If field is a BLOB (Which doesn't support normal DEFAULT)
*/

bool Column_definition::has_default_expression()
{
  return (default_value &&
          (!default_value->expr->basic_const_item() ||
           (flags & BLOB_FLAG)));
}


bool Column_definition::set_compressed(const char *method)
{
  if (!method || !strcmp(method, zlib_compression_method->name))
  {
    unireg_check= Field::TMYSQL_COMPRESSED;
    compression_method_ptr= zlib_compression_method;
    return false;
  }
  my_error(ER_UNKNOWN_COMPRESSION_METHOD, MYF(0), method);
  return true;
}


bool Column_definition::set_compressed_deprecated(THD *thd, const char *method)
{
  push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
                      ER_WARN_DEPRECATED_SYNTAX,
                      ER_THD(thd, ER_WARN_DEPRECATED_SYNTAX),
                      "<data type> <character set clause> ... COMPRESSED...",
                      "'<data type> COMPRESSED... <character set clause> ...'");
  return set_compressed(method);
}


bool
Column_definition::set_compressed_deprecated_column_attribute(THD *thd,
                                                              const char *pos,
                                                              const char *method)
{
  if (compression_method_ptr)
  {
    /*
      Compression method has already been set, e.g.:
        a VARCHAR(10) COMPRESSED DEFAULT 10 COMPRESSED
    */
    thd->parse_error(ER_SYNTAX_ERROR, pos);
    return true;
  }
  enum enum_field_types sql_type= real_field_type();
  /* We can't use f_is_blob here as pack_flag is not yet set */
  if (sql_type == MYSQL_TYPE_VARCHAR || sql_type == MYSQL_TYPE_TINY_BLOB ||
      sql_type == MYSQL_TYPE_BLOB || sql_type == MYSQL_TYPE_MEDIUM_BLOB ||
      sql_type == MYSQL_TYPE_LONG_BLOB)
    return set_compressed_deprecated(thd, method);
  else
    my_error(ER_WRONG_FIELD_SPEC, MYF(0), field_name.str);
  return true;
}


bool Column_definition::check_vcol_for_key(THD *thd) const
{
  if (vcol_info && (vcol_info->flags & VCOL_NOT_STRICTLY_DETERMINISTIC))
  {
    /* use check_expression() to report an error */
    check_expression(vcol_info, &field_name, VCOL_GENERATED_STORED);
    DBUG_ASSERT(thd->is_error());
    return true;
  }
  return false;
}


Send_field::Send_field(THD *thd, Item *item)
{
  item->make_send_field(thd, this);
  normalize();
}


/**
  maximum possible display length for blob.

  @return
    length
*/

uint32 Field_blob::max_display_length() const
{
  switch (packlength)
  {
  case 1:
    return 255 * mbmaxlen();
  case 2:
    return 65535 * mbmaxlen();
  case 3:
    return 16777215 * mbmaxlen();
  case 4:
    return (uint32) UINT_MAX32;
  default:
    DBUG_ASSERT(0); // we should never go here
    return 0;
  }
}


/*****************************************************************************
 Warning handling
*****************************************************************************/

/**
*  Produce warning or note about data saved into field.

  @param level            - level of message (Note/Warning/Error)
  @param code             - error code of message to be produced
  @param cut_increment    - whenever we should increase cut fields count
  @current_row            - current row number

  @note
    This function won't produce warning or notes or increase cut fields counter
    if count_cuted_fields == CHECK_FIELD_IGNORE or CHECK_FIELD_EXPRESSION
    for the current thread.

    This allows us to avoid notes in optimisation, like
    convert_constant_item().

  @retval
    1 if count_cuted_fields == CHECK_FIELD_IGNORE and error level is not NOTE
  @retval
    0 otherwise
*/

bool 
Field::set_warning(Sql_condition::enum_warning_level level, uint code,
                   int cut_increment, ulong current_row) const
{
  /*
    If this field was created only for type conversion purposes it
    will have table == NULL.
  */
  THD *thd= get_thd();

  /*
    In INPLACE ALTER, server can't know which row has generated
    the warning, so the value of current row is supplied by the engine.
  */
  if (current_row)
    thd->get_stmt_da()->reset_current_row_for_warning(current_row);

  if (thd->count_cuted_fields > CHECK_FIELD_EXPRESSION)
  {
    thd->cuted_fields+= cut_increment;
    push_warning_printf(thd, level, code, ER_THD(thd, code), field_name.str,
                        current_row ? current_row
                        : thd->get_stmt_da()->current_row_for_warning());
    return 0;
  }
  return level >= Sql_condition::WARN_LEVEL_WARN;
}


/**
  Produce warning or note about datetime string data saved into field.

  @param level            level of message (Note/Warning/Error)
  @param code             error code of message to be produced
  @param str              string value which we tried to save
  @param ts_type          type of datetime value (datetime/date/time)
  @param cuted_increment  whenever we should increase cut fields count or not

  @note
    This function will always produce some warning but won't increase cut
    fields counter if count_cuted_fields ==FIELD_CHECK_IGNORE for current
    thread.

    See also bug#2336

*/

void Field::set_datetime_warning(Sql_condition::enum_warning_level level,
                                 uint code, const ErrConv *str,
                                 const char *typestr, int cuted_increment)
                                 const
{
  THD *thd= get_thd();
  if (thd->really_abort_on_warning() && level >= Sql_condition::WARN_LEVEL_WARN)
  {
    /*
      field_name.str can be NULL when field is not in the select list:
        SET SESSION SQL_MODE= 'STRICT_ALL_TABLES,NO_ZERO_DATE';
        CREATE OR REPLACE TABLE t2 SELECT 1 AS f FROM t1 GROUP BY FROM_DAYS(d);
      Can't call push_warning_truncated_value_for_field() directly here,
      as it expect a non-NULL name.
    */
    thd->push_warning_wrong_or_truncated_value(level, false, typestr,
                                               str->ptr(),
                                               table->s->db.str,
                                               table->s->table_name.str,
                                               field_name.str);
  }
  else
    set_warning(level, code, cuted_increment);
}


void Field::set_warning_truncated_wrong_value(const char *type_arg,
                                              const char *value)
{
  THD *thd= get_thd();
  const char *db_name;
  const char *table_name;
  /*
    table has in the past been 0 in case of wrong calls when processing
    statistics tables. Let's protect against that.
  */
  DBUG_ASSERT(table);

  db_name= (table && table->s->db.str) ? table->s->db.str : "";
  table_name= (table && table->s->table_name.str) ?
              table->s->table_name.str : "";

  push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
                      ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
                      ER_THD(thd, ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
                      type_arg, value, db_name, table_name, field_name.str,
                      static_cast<ulong>(thd->get_stmt_da()->
                      current_row_for_warning()));
}


/*
  @brief
  Return possible keys for a field

  @details
  Return bit map of keys over this field which can be used by the range
  optimizer. For a field of a generic table such keys are all keys that starts
  from this field. For a field of a materialized derived table/view such keys
  are all keys in which this field takes a part. This is less restrictive as
  keys for a materialized derived table/view are generated on the fly from
  present fields, thus the case when a field for the beginning of a key is
  absent is impossible.

  @return map of possible keys
*/

key_map Field::get_possible_keys()
{
  DBUG_ASSERT(table->pos_in_table_list);
  return (table->pos_in_table_list->is_materialized_derived() ?
          part_of_key : key_start);
}


bool Field::validate_value_in_record_with_warn(THD *thd, const uchar *record)
{
  MY_BITMAP *old_map= dbug_tmp_use_all_columns(table, &table->read_set);
  bool rc;
  if ((rc= validate_value_in_record(thd, record)))
  {
    // Get and report val_str() for the DEFAULT value
    StringBuffer<MAX_FIELD_WIDTH> tmp;
    val_str(&tmp, ptr_in_record(record));
    push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
                        ER_INVALID_DEFAULT_VALUE_FOR_FIELD,
                        ER_THD(thd, ER_INVALID_DEFAULT_VALUE_FOR_FIELD),
                        ErrConvString(&tmp).ptr(), field_name.str);
  }
  dbug_tmp_restore_column_map(&table->read_set, old_map);
  return rc;
}


bool Field::save_in_field_default_value(bool view_error_processing)
{
  THD *thd= table->in_use;

  /*
     TODO: MDEV-19597 Refactor TABLE::vers_update_fields() via stored virtual columns
     This condition will go away as well as other conditions with vers_sys_field().
  */
  if (vers_sys_field())
  {
    if (flags & VERS_ROW_START)
      set_time();
    else
      set_max();
    return false;
  }

  if (unlikely(flags & NO_DEFAULT_VALUE_FLAG &&
               real_type() != MYSQL_TYPE_ENUM))
  {
    if (reset())
    {
      my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
                 ER_THD(thd, ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
      return true;
    }

    if (view_error_processing)
    {
      TABLE_LIST *view= table->pos_in_table_list->top_table();
      push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
                          ER_NO_DEFAULT_FOR_VIEW_FIELD,
                          ER_THD(thd, ER_NO_DEFAULT_FOR_VIEW_FIELD),
                          view->view_db.str,
                          view->view_name.str);
    }
    else
    {
      push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
                          ER_NO_DEFAULT_FOR_FIELD,
                          ER_THD(thd, ER_NO_DEFAULT_FOR_FIELD),
                          field_name.str);
    }
    return true;
  }
  set_default();
  return
    !is_null() &&
    validate_value_in_record_with_warn(thd, table->record[0]) &&
    thd->is_error();
}


bool Field::save_in_field_ignore_value(bool view_error_processing)
{
  enum_sql_command com= table->in_use->lex->sql_command;
  // All insert-like commands
  if (com == SQLCOM_INSERT || com == SQLCOM_REPLACE ||
      com == SQLCOM_INSERT_SELECT || com == SQLCOM_REPLACE_SELECT ||
      com == SQLCOM_LOAD)
    return save_in_field_default_value(view_error_processing);
  return 0; // ignore
}


void Field::register_field_in_read_map()
{
  if (vcol_info)
  {
    Item *vcol_item= vcol_info->expr;
    vcol_item->walk(&Item::register_field_in_read_map, 1, 0);
  }
  bitmap_set_bit(table->read_set, field_index);
}


bool Field::val_str_nopad(MEM_ROOT *mem_root, LEX_CSTRING *to)
{
  StringBuffer<MAX_FIELD_WIDTH> str;
  bool rc= false;
  THD *thd= get_thd();
  Sql_mode_instant_remove sms(thd, MODE_PAD_CHAR_TO_FULL_LENGTH);

  val_str(&str);
  if (!(to->length= str.length()))
    *to= empty_clex_str;
  else if ((rc= !(to->str= strmake_root(mem_root, str.ptr(), str.length()))))
    to->length= 0;

  return rc;
}


void Field::print_key_value(String *out, uint32 length)
{
  if (charset() == &my_charset_bin)
    print_key_value_binary(out, ptr, length);
  else
    val_str(out);
}


void Field_string::print_key_value(String *out, uint32 length)
{
  if (charset() == &my_charset_bin)
  {
    size_t len= field_charset()->lengthsp((const char*) ptr, length);
    print_key_value_binary(out, ptr, static_cast<uint32>(len));
  }
  else
  {
    THD *thd= get_thd();
    sql_mode_t sql_mode_backup= thd->variables.sql_mode;
    thd->variables.sql_mode&= ~MODE_PAD_CHAR_TO_FULL_LENGTH;
    val_str(out,out);
    thd->variables.sql_mode= sql_mode_backup;
  }
}


void Field_varstring::print_key_value(String *out, uint32 length)
{
  if (charset() == &my_charset_bin)
    print_key_value_binary(out, get_data(), get_length());
  else
    val_str(out,out);
}


void Field_blob::print_key_value(String *out, uint32 length)
{
  if (charset() == &my_charset_bin)
  {
    uchar *blob;
    memcpy(&blob, ptr+packlength, sizeof(uchar*));
    print_key_value_binary(out, blob, get_length());
  }
  else
    val_str(out, out);
}


/*
  @brief Print value of the key part

  @param
    out                Output string
    key                value of the key
    length             Length of field in bytes,
                       excluding NULL flag and length bytes
*/


void
Field::print_key_part_value(String *out, const uchar* key, uint32 length)
{
  StringBuffer<128> tmp(system_charset_info);
  uint null_byte= 0;
  if (real_maybe_null())
  {
    /*
      Byte 0 of key is the null-byte. If set, key is NULL.
      Otherwise, print the key value starting immediately after the
      null-byte
    */
    if (*key)
    {
      out->append(NULL_clex_str);
      return;
    }
    null_byte++;  // Skip null byte
  }

  set_key_image(key + null_byte, length);
  print_key_value(&tmp, length);
  if (charset() == &my_charset_bin)
    out->append(tmp.ptr(), tmp.length(), tmp.charset());
  else
    tmp.print(out, system_charset_info);
}


void Field::print_key_value_binary(String *out, const uchar* key, uint32 length)
{
  out->append_semi_hex((const char*)key, length, charset());
}


Virtual_column_info* Virtual_column_info::clone(THD *thd)
{
  Virtual_column_info* dst= new (thd->mem_root) Virtual_column_info(*this);
  if (!dst)
    return NULL;
  if (expr)
  {
    dst->expr= expr->build_clone(thd);
    if (!dst->expr)
      return NULL;
  }
  if (!thd->make_lex_string(&dst->name, name.str, name.length))
    return NULL;
  return dst;
};