summaryrefslogtreecommitdiff
path: root/mysys/ma_dyncol.c
blob: 3c77e5f820a75e405fdf0a4d8798d4f1ef6598d1 (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
/* Copyright (c) 2011, 2013, Monty Program Ab
   Copyright (c) 2011, 2012, Oleksandr Byelkin

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are
   met:

   1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

   2. Redistributions in binary form must the following disclaimer in
     the documentation and/or other materials provided with the
     distribution.

   THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND ANY
   EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   SUCH DAMAGE.
*/

/*
 Numeric format:
 ===============
  * Fixed header part
    1 byte flags:
      0,1 bits - <offset size> - 1
      2-7 bits - 0
    2 bytes column counter
  * Columns directory sorted by column number, each entry contains of:
    2 bytes column number
    <offset size> bytes (1-4) combined offset from beginning of
      the data segment + 3 bit type
  * Data of above columns size of data and length depend on type

 Columns with names:
 ===================
  * Fixed header part
    1 byte flags:
      0,1 bits - <offset size> - 2
      2 bit    - 1 (means format with names)
      3,4 bits - 00 (means <names offset size> - 2,
                     now 2 is the only supported size)
      5-7 bits - 0
    2 bytes column counter
  * Variable header part (now it is actually fixed part)
    <names offset size> (2) bytes size of stored names pool
  * Column directory sorted by names, each consists of
    <names offset size> (2) bytes offset of name
    <offset size> bytes (2-5)bytes combined offset from beginning of
      the data segment + 4 bit type
  * Names stored one after another
  * Data of above columns size of data and length depend on type
*/

#include "mysys_priv.h"
#include <m_string.h>
#include <ma_dyncol.h>
#include <my_time.h>

uint32 copy_and_convert(char *to, uint32 to_length, CHARSET_INFO *to_cs,
			const char *from, uint32 from_length,
			CHARSET_INFO *from_cs, uint *errors);
/*
  Flag byte bits

  2 bits which determinate size of offset in the header -1
*/
/* mask to get above bits */
#define DYNCOL_FLG_OFFSET   (1|2)
#define DYNCOL_FLG_NAMES    4
#define DYNCOL_FLG_NMOFFSET (8|16)
/**
  All known flags mask that could be set.

  @note DYNCOL_FLG_NMOFFSET should be 0 for now.
*/
#define DYNCOL_FLG_KNOWN  (1|2|4)

/* formats */
enum enum_dyncol_format
{
  dyncol_fmt_num= 0,
  dyncol_fmt_str= 1
};

/* dynamic column size reserve */
#define DYNCOL_SYZERESERVE 80

#define DYNCOL_OFFSET_ERROR 0xffffffff

/* length of fixed string header 1 byte - flags, 2 bytes - columns counter */
#define FIXED_HEADER_SIZE 3
/*
  length of fixed string header with names
  1 byte - flags, 2 bytes - columns counter,  2 bytes - name pool size
*/
#define FIXED_HEADER_SIZE_NM 5

#define COLUMN_NUMBER_SIZE 2
/* 2 bytes offset from the name pool */
#define COLUMN_NAMEPTR_SIZE 2

#define MAX_OFFSET_LENGTH    4
#define MAX_OFFSET_LENGTH_NM 5

#define DYNCOL_NUM_CHAR 6

my_bool mariadb_dyncol_has_names(DYNAMIC_COLUMN *str)
{
  if (str->length < 1)
    return FALSE;
  return test(str->str[0] & DYNCOL_FLG_NAMES);
}

static enum enum_dyncol_func_result
dynamic_column_time_store(DYNAMIC_COLUMN *str,
                          MYSQL_TIME *value, enum enum_dyncol_format format);
static enum enum_dyncol_func_result
dynamic_column_date_store(DYNAMIC_COLUMN *str,
                          MYSQL_TIME *value);
static enum enum_dyncol_func_result
dynamic_column_time_read_internal(DYNAMIC_COLUMN_VALUE *store_it_here,
                                  uchar *data, size_t length);
static enum enum_dyncol_func_result
dynamic_column_date_read_internal(DYNAMIC_COLUMN_VALUE *store_it_here,
                                  uchar *data, size_t length);
static enum enum_dyncol_func_result
dynamic_column_get_internal(DYNAMIC_COLUMN *str,
                                DYNAMIC_COLUMN_VALUE *store_it_here,
                                uint num_key, LEX_STRING *str_key);
static enum enum_dyncol_func_result
dynamic_column_exists_internal(DYNAMIC_COLUMN *str, uint num_key,
                               LEX_STRING *str_key);
static enum enum_dyncol_func_result
dynamic_column_update_many_fmt(DYNAMIC_COLUMN *str,
                               uint add_column_count,
                               void *column_keys,
                               DYNAMIC_COLUMN_VALUE *values,
                               my_bool string_keys);
static int plan_sort_num(const void *a, const void *b);
static int plan_sort_named(const void *a, const void *b);

/*
  Structure to hold information about dynamic columns record and
  iterate through it.
*/

struct st_dyn_header
{
  uchar *header, *nmpool, *dtpool, *data_end;
  size_t offset_size;
  size_t entry_size;
  size_t header_size;
  size_t nmpool_size;
  size_t data_size;
  /* dyncol_fmt_num - numeric columns, dyncol_fmt_str - column names */
  enum enum_dyncol_format format;
  uint column_count;

  uchar *entry, *data, *name;
  size_t offset;
  size_t length;
  enum enum_dynamic_column_type type;
};

typedef struct st_dyn_header DYN_HEADER;

static inline my_bool read_fixed_header(DYN_HEADER *hdr,
                                        DYNAMIC_COLUMN *str);
static void set_fixed_header(DYNAMIC_COLUMN *str,
                             uint offset_size,
                             uint column_count);

/*
  Calculate entry size (E) and header size (H) by offset size (O) and column
  count (C) and fixed part of entry size (F).
*/

#define calc_param(E,H,F,O,C) do { \
  (*(E))= (O) + F;                 \
  (*(H))= (*(E)) * (C);            \
}while(0);


/**
  Name pool size functions, for numeric format it is 0
*/

static size_t name_size_num(void *keys __attribute__((unused)),
                            uint i __attribute__((unused)))
{
  return 0;
}


/**
  Name pool size functions.
*/
static size_t name_size_named(void *keys, uint i)
{
  return ((LEX_STRING *) keys)[i].length;
}


/**
  Comparator function for references on column numbers for qsort
  (numeric format)
*/

static int column_sort_num(const void *a, const void *b)
{
  return **((uint **)a) - **((uint **)b);
}

/**
  Comparator function for references on column numbers for qsort
  (names format)
*/

int mariadb_dyncol_column_cmp_named(const LEX_STRING *s1, const LEX_STRING *s2)
{
  /*
    We compare instead of subtraction to avoid data loss in case of huge
    length difference (more then fit in int).
  */
  int rc= (s1->length > s2->length ? 1 :
           (s1->length < s2->length ? -1 : 0));
  if (rc == 0)
    rc= memcmp((void *)s1->str, (void *)s2->str,
               (size_t) s1->length);
  return rc;
}


/**
  Comparator function for references on column numbers for qsort
  (names format)
*/

static int column_sort_named(const void *a, const void *b)
{
  return mariadb_dyncol_column_cmp_named(*((LEX_STRING **)a),
                                         *((LEX_STRING **)b));
}


/**
  Check limit function (numeric format)
*/

static my_bool check_limit_num(const void *val)
{
  return **((uint **)val) > UINT_MAX16;
}


/**
  Check limit function (names format)
*/

static my_bool check_limit_named(const void *val)
{
  return (*((LEX_STRING **)val))->length > MAX_NAME_LENGTH;
}


/**
  Write numeric format static header part.
*/

static void set_fixed_header_num(DYNAMIC_COLUMN *str, DYN_HEADER *hdr)
{
  set_fixed_header(str, (uint)hdr->offset_size, hdr->column_count);
  hdr->header= (uchar *)str->str + FIXED_HEADER_SIZE;
  hdr->nmpool= hdr->dtpool= hdr->header + hdr->header_size;
}


/**
  Write names format static header part.
*/

static void set_fixed_header_named(DYNAMIC_COLUMN *str, DYN_HEADER *hdr)
{
  DBUG_ASSERT(hdr->column_count <= 0xffff);
  DBUG_ASSERT(hdr->offset_size <= MAX_OFFSET_LENGTH_NM);
  /* size of data offset, named format flag, size of names offset (0 means 2) */
  str->str[0]=
    (char) ((str->str[0] & ~(DYNCOL_FLG_OFFSET | DYNCOL_FLG_NMOFFSET)) |
            (hdr->offset_size - 2) | DYNCOL_FLG_NAMES);
  int2store(str->str + 1, hdr->column_count);        /* columns number */
  int2store(str->str + 3, hdr->nmpool_size);
  hdr->header= (uchar *)str->str + FIXED_HEADER_SIZE_NM;
  hdr->nmpool= hdr->header + hdr->header_size;
  hdr->dtpool= hdr->nmpool + hdr->nmpool_size;
}


/**
  Store offset and type information in the given place

  @param place           Beginning of the index entry
  @param offset_size     Size of offset field in bytes
  @param type            Type to be written
  @param offset          Offset to be written
*/

static my_bool type_and_offset_store_num(uchar *place, size_t offset_size,
                                         DYNAMIC_COLUMN_TYPE type,
                                         size_t offset)
{
  ulong val = (((ulong) offset) << 3) | (type - 1);
  DBUG_ASSERT(type != DYN_COL_NULL);
  DBUG_ASSERT(((type - 1) & (~7)) == 0); /* fit in 3 bits */
  DBUG_ASSERT(offset_size >= 1 && offset_size <= 4);

  /* Index entry starts with column number; jump over it */
  place+= COLUMN_NUMBER_SIZE;

  switch (offset_size) {
  case 1:
    if (offset >= 0x1f)          /* all 1 value is reserved */
      return TRUE;
    place[0]= (uchar)val;
    break;
  case 2:
    if (offset >= 0x1fff)        /* all 1 value is reserved */
      return TRUE;
    int2store(place, val);
    break;
  case 3:
    if (offset >= 0x1fffff)      /* all 1 value is reserved */
      return TRUE;
    int3store(place, val);
    break;
  case 4:
    if (offset >= 0x1fffffff)    /* all 1 value is reserved */
      return TRUE;
    int4store(place, val);
    break;
  default:
      return TRUE;
  }
  return FALSE;
}


static my_bool type_and_offset_store_named(uchar *place, size_t offset_size,
                                           DYNAMIC_COLUMN_TYPE type,
                                           size_t offset)
{
  ulonglong val = (((ulong) offset) << 4) | (type - 1);
  DBUG_ASSERT(type != DYN_COL_NULL);
  DBUG_ASSERT(((type - 1) & (~0xf)) == 0); /* fit in 4 bits */
  DBUG_ASSERT(offset_size >= 2 && offset_size <= 5);

  /* Index entry starts with name offset; jump over it */
  place+= COLUMN_NAMEPTR_SIZE;
  switch (offset_size) {
  case 2:
    if (offset >= 0xfff)          /* all 1 value is reserved */
      return TRUE;
    int2store(place, val);
    break;
  case 3:
    if (offset >= 0xfffff)        /* all 1 value is reserved */
      return TRUE;
    int3store(place, val);
    break;
  case 4:
    if (offset >= 0xfffffff)      /* all 1 value is reserved */
      return TRUE;
    int4store(place, val);
    break;
  case 5:
#if SIZEOF_SIZE_T > 4
    if (offset >= 0xfffffffffull)    /* all 1 value is reserved */
      return TRUE;
#endif
    int5store(place, val);
    break;
  case 1:
  default:
      return TRUE;
  }
  return FALSE;
}

/**
  Write numeric format header entry
   2 bytes - column number
   1-4 bytes - data offset combined with type

  @param hdr             descriptor of dynamic column record
  @param column_key      pointer to uint (column number)
  @param value           value which will be written (only type used)
  @param offset          offset of the data
*/

static my_bool put_header_entry_num(DYN_HEADER *hdr,
                                    void *column_key,
                                    DYNAMIC_COLUMN_VALUE *value,
                                    size_t offset)
{
  uint *column_number= (uint *)column_key;
  int2store(hdr->entry, *column_number);
  DBUG_ASSERT(hdr->nmpool_size == 0);
  if (type_and_offset_store_num(hdr->entry, hdr->offset_size,
                                value->type,
                                offset))
      return TRUE;
  hdr->entry= hdr->entry + hdr->entry_size;
  return FALSE;
}


/**
  Write names format header entry
   1 byte - name length
   2 bytes - name offset in the name pool
   1-4 bytes - data offset combined with type

  @param hdr             descriptor of dynamic column record
  @param column_key      pointer to LEX_STRING (column name)
  @param value           value which will be written (only type used)
  @param offset          offset of the data
*/

static my_bool put_header_entry_named(DYN_HEADER *hdr,
                                      void *column_key,
                                      DYNAMIC_COLUMN_VALUE *value,
                                      size_t offset)
{
  LEX_STRING *column_name= (LEX_STRING *)column_key;
  DBUG_ASSERT(column_name->length <= MAX_NAME_LENGTH);
  DBUG_ASSERT(hdr->name - hdr->nmpool < (long) 0x10000L);
  int2store(hdr->entry, hdr->name - hdr->nmpool);
  memcpy(hdr->name, column_name->str, column_name->length);
  DBUG_ASSERT(hdr->nmpool_size != 0 || column_name->length == 0);
  if (type_and_offset_store_named(hdr->entry, hdr->offset_size,
                                  value->type,
                                  offset))
    return TRUE;
  hdr->entry+= hdr->entry_size;
  hdr->name+= column_name->length;
  return FALSE;
}


/**
  Calculate length of offset field for given data length

  @param data_length     Length of the data segment

  @return number of bytes
*/

static size_t dynamic_column_offset_bytes_num(size_t data_length)
{
  if (data_length < 0x1f)                /* all 1 value is reserved */
    return 1;
  if (data_length < 0x1fff)              /* all 1 value is reserved */
    return 2;
  if (data_length < 0x1fffff)            /* all 1 value is reserved */
    return 3;
  if (data_length < 0x1fffffff)          /* all 1 value is reserved */
    return 4;
  return MAX_OFFSET_LENGTH + 1;          /* For an error generation*/
}

static size_t dynamic_column_offset_bytes_named(size_t data_length)
{
  if (data_length < 0xfff)                /* all 1 value is reserved */
    return 2;
  if (data_length < 0xfffff)              /* all 1 value is reserved */
    return 3;
  if (data_length < 0xfffffff)            /* all 1 value is reserved */
    return 4;
#if SIZEOF_SIZE_T > 4
  if (data_length < 0xfffffffffull)       /* all 1 value is reserved */
#endif
    return 5;
  return MAX_OFFSET_LENGTH_NM + 1;        /* For an error generation */
}

/**
  Read offset and type information from index entry

  @param type            Where to put type info
  @param offset          Where to put offset info
  @param place           beginning of the type and offset
  @param offset_size     Size of offset field in bytes
*/

static my_bool type_and_offset_read_num(DYNAMIC_COLUMN_TYPE *type,
                                        size_t *offset,
                                        uchar *place, size_t offset_size)
{
  ulong UNINIT_VAR(val);
  ulong UNINIT_VAR(lim);

  DBUG_ASSERT(offset_size >= 1 && offset_size <= 4);

  switch (offset_size) {
  case 1:
    val= (ulong)place[0];
    lim= 0x1f;
    break;
  case 2:
    val= uint2korr(place);
    lim= 0x1fff;
    break;
  case 3:
    val= uint3korr(place);
    lim= 0x1fffff;
    break;
  case 4:
    val= uint4korr(place);
    lim= 0x1fffffff;
    break;
  default:
    DBUG_ASSERT(0);                             /* impossible */
    return 1;
  }
  *type= (val & 0x7) + 1;
  *offset= val >> 3;
  return (*offset >= lim);
}

static my_bool type_and_offset_read_named(DYNAMIC_COLUMN_TYPE *type,
                                          size_t *offset,
                                          uchar *place, size_t offset_size)
{
  ulonglong UNINIT_VAR(val);
  ulonglong UNINIT_VAR(lim);
  DBUG_ASSERT(offset_size >= 2 && offset_size <= 5);

  switch (offset_size) {
  case 2:
    val= uint2korr(place);
    lim= 0xfff;
    break;
  case 3:
    val= uint3korr(place);
    lim= 0xfffff;
    break;
  case 4:
    val= uint4korr(place);
    lim= 0xfffffff;
    break;
  case 5:
    val= uint5korr(place);
    lim= 0xfffffffffull;
    break;
  case 1:
  default:
    DBUG_ASSERT(0);                             /* impossible */
    return 1;
  }
  *type= (val & 0xf) + 1;
  *offset= val >> 4;
  return (*offset >= lim);
}

/**
  Format descriptor, contain constants and function references for
  format processing
*/

struct st_service_funcs
{
  /* size of fixed header */
  uint fixed_hdr;
  /* size of fixed part of header entry */
  uint fixed_hdr_entry;

  /*size of array element which stores keys */
  uint key_size_in_array;

  /* Maximum data offset size in bytes */
  size_t max_offset_size;

  size_t (*name_size)
    (void *, uint);
  int (*column_sort)
    (const void *a, const void *b);
  my_bool (*check_limit)
    (const void *val);
  void (*set_fixed_hdr)
    (DYNAMIC_COLUMN *str, DYN_HEADER *hdr);
  my_bool (*put_header_entry)(DYN_HEADER *hdr,
                              void *column_key,
                              DYNAMIC_COLUMN_VALUE *value,
                              size_t offset);
  int (*plan_sort)(const void *a, const void *b);
  size_t (*dynamic_column_offset_bytes)(size_t data_length);
  my_bool (*type_and_offset_read)(DYNAMIC_COLUMN_TYPE *type,
                                  size_t *offset,
                                  uchar *place, size_t offset_size);

};


/**
  Actual our 2 format descriptors
*/

static struct st_service_funcs fmt_data[2]=
{
  {
    FIXED_HEADER_SIZE,
    COLUMN_NUMBER_SIZE,
    sizeof(uint),
    MAX_OFFSET_LENGTH,
    &name_size_num,
    &column_sort_num,
    &check_limit_num,
    &set_fixed_header_num,
    &put_header_entry_num,
    &plan_sort_num,
    &dynamic_column_offset_bytes_num,
    &type_and_offset_read_num
  },
  {
    FIXED_HEADER_SIZE_NM,
    COLUMN_NAMEPTR_SIZE,
    sizeof(LEX_STRING),
    MAX_OFFSET_LENGTH_NM,
    &name_size_named,
    &column_sort_named,
    &check_limit_named,
    &set_fixed_header_named,
    &put_header_entry_named,
    &plan_sort_named,
    &dynamic_column_offset_bytes_named,
    &type_and_offset_read_named
  }
};


/**
  Read dynamic column record header and fill the descriptor

  @param hdr             dynamic columns record descriptor to fill
  @param str             dynamic columns record

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
init_read_hdr(DYN_HEADER *hdr, DYNAMIC_COLUMN *str)
{
  if (read_fixed_header(hdr, str))
    return ER_DYNCOL_FORMAT;
  hdr->header= (uchar*)str->str + fmt_data[hdr->format].fixed_hdr;
  calc_param(&hdr->entry_size, &hdr->header_size,
             fmt_data[hdr->format].fixed_hdr_entry, hdr->offset_size,
             hdr->column_count);
  hdr->nmpool= hdr->header + hdr->header_size;
  hdr->dtpool= hdr->nmpool + hdr->nmpool_size;
  hdr->data_size= str->length - fmt_data[hdr->format].fixed_hdr -
    hdr->header_size - hdr->nmpool_size;
  hdr->data_end= (uchar*)str->str + str->length;
  return ER_DYNCOL_OK;
}


/**
  Initialize dynamic column string with (make it empty but correct format)

  @param str             The string to initialize
  @param size            Amount of preallocated memory for the string.

  @retval FALSE OK
  @retval TRUE  error
*/

static my_bool dynamic_column_init_named(DYNAMIC_COLUMN *str, size_t size)
{
  DBUG_ASSERT(size != 0);

  /*
    Make string with no fields (empty header)
    - First \0 is flags
    - other 2 \0 is number of fields
  */
  if (init_dynamic_string(str, NULL, size, DYNCOL_SYZERESERVE))
    return TRUE;
  return FALSE;
}


/**
  Calculate how many bytes needed to store val as variable length integer
  where first bit indicate continuation of the sequence.

  @param val             The value for which we are calculating length

  @return number of bytes
*/

static size_t dynamic_column_var_uint_bytes(ulonglong val)
{
  size_t len= 0;
  do
  {
    len++;
    val>>= 7;
  } while (val);
  return len;
}


/**
   Stores variable length unsigned integer value to a string

  @param str             The string where to append the value
  @param val             The value to put in the string

  @return ER_DYNCOL_* return code

  @notes
  This is used to store a number together with other data in the same
  object.  (Like decimals, length of string etc)
  (As we don't know the length of this object, we can't store 0 in 0 bytes)
*/

static enum enum_dyncol_func_result
dynamic_column_var_uint_store(DYNAMIC_COLUMN *str, ulonglong val)
{
  if (dynstr_realloc(str, 10))                  /* max what we can use */
    return ER_DYNCOL_RESOURCE;

  do
  {
    ulonglong rest= val >> 7;
    str->str[str->length++]= ((val & 0x7f) | (rest ? 0x80 : 0x00));
    val= rest;
  } while (val);
  return ER_DYNCOL_OK;
}


/**
  Reads variable length unsigned integer value from a string

  @param data            The string from which the int should be read
  @param data_length	 Max length of data
  @param len             Where to put length of the string read in bytes

  @return value of the unsigned integer read from the string

  In case of error, *len is set to 0
*/

static ulonglong
dynamic_column_var_uint_get(uchar *data, size_t data_length,
                            size_t *len)
{
  ulonglong val= 0;
  uint length;
  uchar *end= data + data_length;

  for (length=0; data < end ; data++)
  {
    val+= (((ulonglong)((*data) & 0x7f)) << (length * 7));
    length++;
    if (!((*data) & 0x80))
    {
      /* End of data */
      *len= length;
      return val;
    }
  }
  /* Something was wrong with data */
  *len= 0;                                      /* Mark error */
  return 0;
}


/**
  Calculate how many bytes needed to store val as unsigned.

  @param val             The value for which we are calculating length

  @return number of bytes (0-8)
*/

static size_t dynamic_column_uint_bytes(ulonglong val)
{
  size_t len;

  for (len= 0; val ; val>>= 8, len++)
    ;
  return len;
}


/**
  Append the string with given unsigned int value.

  @param str             The string where to put the value
  @param val             The value to put in the string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_uint_store(DYNAMIC_COLUMN *str, ulonglong val)
{
  if (dynstr_realloc(str, 8)) /* max what we can use */
    return ER_DYNCOL_RESOURCE;

  for (; val; val>>= 8)
    str->str[str->length++]= (char) (val & 0xff);
  return ER_DYNCOL_OK;
}


/**
  Read unsigned int value of given length from the string

  @param store_it_here   The structure to store the value
  @param data            The string which should be read
  @param length          The length (in bytes) of the value in nthe string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_uint_read(DYNAMIC_COLUMN_VALUE *store_it_here,
                         uchar *data, size_t length)
{
  ulonglong value= 0;
  size_t i;

  for (i= 0; i < length; i++)
    value+= ((ulonglong)data[i]) << (i*8);

  store_it_here->x.ulong_value= value;
  return ER_DYNCOL_OK;
}

/**
  Calculate how many bytes needed to store val as signed in following encoding:
    0 -> 0
   -1 -> 1
    1 -> 2
   -2 -> 3
    2 -> 4
   ...

  @param val             The value for which we are calculating length

  @return number of bytes
*/

static size_t dynamic_column_sint_bytes(longlong val)
{
  return dynamic_column_uint_bytes((val << 1) ^
                                   (val < 0 ? 0xffffffffffffffffull : 0));
}


/**
  Append the string with given signed int value.

  @param str             the string where to put the value
  @param val             the value to put in the string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_sint_store(DYNAMIC_COLUMN *str, longlong val)
{
  return dynamic_column_uint_store(str,
                                 (val << 1) ^
                                 (val < 0 ? 0xffffffffffffffffULL : 0));
}


/**
  Read signed int value of given length from the string

  @param store_it_here   The structure to store the value
  @param data            The string which should be read
  @param length          The length (in bytes) of the value in the string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_sint_read(DYNAMIC_COLUMN_VALUE *store_it_here,
                         uchar *data, size_t length)
{
  ulonglong val;
  dynamic_column_uint_read(store_it_here, data, length);
  val= store_it_here->x.ulong_value;
  if (val & 1)
    val= (val >> 1) ^ 0xffffffffffffffffULL;
  else
    val>>= 1;
  store_it_here->x.long_value= (longlong) val;
  return ER_DYNCOL_OK;
}


/**
  Calculate how many bytes needed to store the value.

  @param value          The value for which we are calculating length

  @return
  Error:  (size_t) ~0
  ok      number of bytes
*/

static size_t
dynamic_column_value_len(DYNAMIC_COLUMN_VALUE *value,
                         enum enum_dyncol_format format)
{
  switch (value->type) {
  case DYN_COL_NULL:
    return 0;
  case DYN_COL_INT:
    return dynamic_column_sint_bytes(value->x.long_value);
  case DYN_COL_UINT:
    return dynamic_column_uint_bytes(value->x.ulong_value);
  case DYN_COL_DOUBLE:
    return 8;
  case DYN_COL_STRING:
    return (dynamic_column_var_uint_bytes(value->x.string.charset->number) +
            value->x.string.value.length);
  case DYN_COL_DECIMAL:
  {
    int precision= value->x.decimal.value.intg + value->x.decimal.value.frac;
    int scale= value->x.decimal.value.frac;

    if (precision == 0 || decimal_is_zero(&value->x.decimal.value))
    {
      /* This is here to simplify dynamic_column_decimal_store() */
      value->x.decimal.value.intg= value->x.decimal.value.frac= 0;
      return 0;
    }
    /*
      Check if legal decimal;  This is needed to not get an assert in
      decimal_bin_size(). However this should be impossible as all
      decimals entered here should be valid and we have the special check
      above to handle the unlikely but possible case that decimal.value.intg
      and decimal.frac is 0.
    */
    if (scale < 0 || precision <= 0)
    {
      DBUG_ASSERT(0);                           /* Impossible */
      return (size_t) ~0;
    }
    return (dynamic_column_var_uint_bytes(value->x.decimal.value.intg) +
            dynamic_column_var_uint_bytes(value->x.decimal.value.frac) +
            decimal_bin_size(precision, scale));
  }
  case DYN_COL_DATETIME:
    if (format == dyncol_fmt_num || value->x.time_value.second_part)
      /* date+time in bits: 14 + 4 + 5 + 10 + 6 + 6 + 20 + 1 66bits ~= 9 bytes*/
      return 9;
    else
      return 6;
  case DYN_COL_DATE:
    /* date in dits: 14 + 4 + 5 = 23bits ~= 3bytes*/
    return 3;
  case DYN_COL_TIME:
    if (format == dyncol_fmt_num || value->x.time_value.second_part)
      /* time in bits: 10 + 6 + 6 + 20 + 1 = 43bits ~= 6bytes*/
      return 6;
    else
      return 3;
  case DYN_COL_DYNCOL:
    return value->x.string.value.length;
  }
  DBUG_ASSERT(0);
  return 0;
}


/**
  Append double value to a string

  @param str             the string where to put the value
  @param val             the value to put in the string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_double_store(DYNAMIC_COLUMN *str, double val)
{
   if (dynstr_realloc(str, 8))
     return ER_DYNCOL_RESOURCE;
   float8store(str->str + str->length, val);
   str->length+= 8;
   return ER_DYNCOL_OK;
}


/**
  Read double value of given length from the string

  @param store_it_here   The structure to store the value
  @param data            The string which should be read
  @param length          The length (in bytes) of the value in nthe string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_double_read(DYNAMIC_COLUMN_VALUE *store_it_here,
                               uchar *data, size_t length)
{
  if (length != 8)
    return ER_DYNCOL_FORMAT;
  float8get(store_it_here->x.double_value, data);
  return ER_DYNCOL_OK;
}


/**
  Append the string with given string value.

  @param str             the string where to put the value
  @param val             the value to put in the string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_string_store(DYNAMIC_COLUMN *str, LEX_STRING *string,
                            CHARSET_INFO *charset)
{
  enum enum_dyncol_func_result rc;
  if ((rc= dynamic_column_var_uint_store(str, charset->number)))
    return rc;
  if (dynstr_append_mem(str, string->str, string->length))
    return ER_DYNCOL_RESOURCE;
  return ER_DYNCOL_OK;
}

/**
  Append the string with given string value.

  @param str             the string where to put the value
  @param val             the value to put in the string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_dyncol_store(DYNAMIC_COLUMN *str, LEX_STRING *string)
{
  if (dynstr_append_mem(str, string->str, string->length))
    return ER_DYNCOL_RESOURCE;
  return ER_DYNCOL_OK;
}

/**
  Read string value of given length from the packed string

  @param store_it_here   The structure to store the value
  @param data            The packed string which should be read
  @param length          The length (in bytes) of the value in nthe string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_string_read(DYNAMIC_COLUMN_VALUE *store_it_here,
                           uchar *data, size_t length)
{
  size_t len;
  uint charset_nr= (uint)dynamic_column_var_uint_get(data, length, &len);
  if (len == 0)                                /* Wrong packed number */
    return ER_DYNCOL_FORMAT;
  store_it_here->x.string.charset= get_charset(charset_nr, MYF(MY_WME));
  if (store_it_here->x.string.charset == NULL)
    return ER_DYNCOL_UNKNOWN_CHARSET;
  data+= len;
  store_it_here->x.string.value.length= (length-= len);
  store_it_here->x.string.value.str= (char*) data;
  return ER_DYNCOL_OK;
}

/**
  Read Dynamic columns packet string value of given length
  from the packed string

  @param store_it_here   The structure to store the value
  @param data            The packed string which should be read
  @param length          The length (in bytes) of the value in nthe string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_dyncol_read(DYNAMIC_COLUMN_VALUE *store_it_here,
                           uchar *data, size_t length)
{
  store_it_here->x.string.charset= &my_charset_bin;
  store_it_here->x.string.value.length= length;
  store_it_here->x.string.value.str= (char*) data;
  return ER_DYNCOL_OK;
}

/**
  Append the string with given decimal value.

  @param str             the string where to put the value
  @param val             the value to put in the string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_decimal_store(DYNAMIC_COLUMN *str,
                             decimal_t *value)
{
  uint bin_size;
  int precision= value->intg + value->frac;
  
  /* Store decimal zero as empty string */
  if (precision == 0)
    return ER_DYNCOL_OK;

  bin_size= decimal_bin_size(precision, value->frac);
  if (dynstr_realloc(str, bin_size + 20))
    return ER_DYNCOL_RESOURCE;

  /* The following can't fail as memory is already allocated */
  (void) dynamic_column_var_uint_store(str, value->intg);
  (void) dynamic_column_var_uint_store(str, value->frac);

  decimal2bin(value, (uchar *) str->str + str->length,
              precision, value->frac);
  str->length+= bin_size;
  return ER_DYNCOL_OK;
}


/**
  Prepare the value to be used as decimal.

  @param value           The value structure which sould be setup.
*/

void mariadb_dyncol_prepare_decimal(DYNAMIC_COLUMN_VALUE *value)
{
  value->x.decimal.value.buf= value->x.decimal.buffer;
  value->x.decimal.value.len= DECIMAL_BUFF_LENGTH;
  /* just to be safe */
  value->type= DYN_COL_DECIMAL;
  decimal_make_zero(&value->x.decimal.value);
}

void dynamic_column_prepare_decimal(DYNAMIC_COLUMN_VALUE *value)
{
  mariadb_dyncol_prepare_decimal(value);
}



/**
  Read decimal value of given length from the string

  @param store_it_here   The structure to store the value
  @param data            The string which should be read
  @param length          The length (in bytes) of the value in nthe string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_decimal_read(DYNAMIC_COLUMN_VALUE *store_it_here,
                            uchar *data, size_t length)
{
  size_t intg_len, frac_len;
  int intg, frac, precision, scale;

  dynamic_column_prepare_decimal(store_it_here);
  /* Decimals 0.0 is stored as a zero length string */
  if (length == 0)
    return ER_DYNCOL_OK;                        /* value contains zero */

  intg= (int)dynamic_column_var_uint_get(data, length, &intg_len);
  data+= intg_len;
  frac= (int)dynamic_column_var_uint_get(data, length - intg_len, &frac_len);
  data+= frac_len;

  /* Check the size of data is correct */
  precision= intg + frac;
  scale=     frac;
  if (scale < 0 || precision <= 0 || scale > precision ||
      (length - intg_len - frac_len) >
      (size_t) (DECIMAL_BUFF_LENGTH*sizeof(decimal_digit_t)) ||
      decimal_bin_size(intg + frac, frac) !=
      (int) (length - intg_len - frac_len))
    return ER_DYNCOL_FORMAT;

  if (bin2decimal(data, &store_it_here->x.decimal.value, precision, scale) !=
      E_DEC_OK)
    return ER_DYNCOL_FORMAT;
  return ER_DYNCOL_OK;
}


/**
  Append the string with given datetime value.

  @param str             the string where to put the value
  @param value           the value to put in the string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_date_time_store(DYNAMIC_COLUMN *str, MYSQL_TIME *value,
                               enum enum_dyncol_format format)
{
  enum enum_dyncol_func_result rc;
  /*
    0<----year----><mn><day>00000!<-hours--><min-><sec-><---microseconds--->
     12345678901234123412345     1123456789012345612345612345678901234567890
    <123456><123456><123456><123456><123456><123456><123456><123456><123456>
  */
  if ((rc= dynamic_column_date_store(str, value)) ||
      (rc= dynamic_column_time_store(str, value, format)))
    return rc;
  return ER_DYNCOL_OK;
}


/**
  Read datetime value of given length from the packed string

  @param store_it_here   The structure to store the value
  @param data            The packed string which should be read
  @param length          The length (in bytes) of the value in nthe string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_date_time_read(DYNAMIC_COLUMN_VALUE *store_it_here,
                              uchar *data, size_t length)
{
  enum enum_dyncol_func_result rc= ER_DYNCOL_FORMAT;
  /*
    0<----year----><mn><day>00000!<-hours--><min-><sec-><---microseconds--->
     12345678901234123412345     1123456789012345612345612345678901234567890
    <123456><123456><123456><123456><123456><123456><123456><123456><123456>
  */
  if (length != 9 && length != 6)
    goto err;
  store_it_here->x.time_value.time_type= MYSQL_TIMESTAMP_DATETIME;
  if ((rc= dynamic_column_date_read_internal(store_it_here, data, 3)) ||
      (rc= dynamic_column_time_read_internal(store_it_here, data + 3,
                                             length - 3)))
    goto err;
  return ER_DYNCOL_OK;

err:
  store_it_here->x.time_value.time_type= MYSQL_TIMESTAMP_ERROR;
  return rc;
}


/**
  Append the string with given time value.

  @param str             the string where to put the value
  @param value           the value to put in the string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_time_store(DYNAMIC_COLUMN *str, MYSQL_TIME *value,
                          enum enum_dyncol_format format)
{
  uchar *buf;
  if (dynstr_realloc(str, 6))
    return ER_DYNCOL_RESOURCE;

  buf= ((uchar *)str->str) + str->length;

  if (value->time_type == MYSQL_TIMESTAMP_NONE ||
      value->time_type == MYSQL_TIMESTAMP_ERROR ||
      value->time_type == MYSQL_TIMESTAMP_DATE)
  {
    value->neg= 0;
    value->second_part= 0;
    value->hour= 0;
    value->minute= 0;
    value->second= 0;
  }
  DBUG_ASSERT(value->hour <= 838);
  DBUG_ASSERT(value->minute <= 59);
  DBUG_ASSERT(value->second <= 59);
  DBUG_ASSERT(value->second_part <= 999999);
  if (format == dyncol_fmt_num || value->second_part)
  {
  /*
    00000!<-hours--><min-><sec-><---microseconds--->
         1123456789012345612345612345678901234567890
    <123456><123456><123456><123456><123456><123456>
  */
    buf[0]= (value->second_part & 0xff);
    buf[1]= ((value->second_part & 0xff00) >> 8);
    buf[2]= (uchar)(((value->second & 0xf) << 4) |
                    ((value->second_part & 0xf0000) >> 16));
    buf[3]= ((value->minute << 2) | ((value->second & 0x30) >> 4));
    buf[4]= (value->hour & 0xff);
    buf[5]= ((value->neg ? 0x4 : 0) | (value->hour >> 8));
    str->length+= 6;
  }
  else
  {
  /*
     !<-hours--><min-><sec->
     11234567890123456123456
    <123456><123456><123456>
  */
    buf[0]= (value->second) | ((value->minute & 0x3) << 6);
    buf[1]= (value->minute >> 2) | ((value->hour & 0xf) << 4);
    buf[2]= (value->hour >> 4) | (value->neg ? 0x80 : 0);
    str->length+= 3;
  }

  return ER_DYNCOL_OK;
}


/**
  Read time value of given length from the packed string

  @param store_it_here   The structure to store the value
  @param data            The packed string which should be read
  @param length          The length (in bytes) of the value in nthe string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_time_read(DYNAMIC_COLUMN_VALUE *store_it_here,
                         uchar *data, size_t length)
{
  store_it_here->x.time_value.year= store_it_here->x.time_value.month=
    store_it_here->x.time_value.day= 0;
  store_it_here->x.time_value.time_type= MYSQL_TIMESTAMP_TIME;
  return dynamic_column_time_read_internal(store_it_here, data, length);
}

/**
  Internal function for reading time part from the string.

  @param store_it_here   The structure to store the value
  @param data            The packed string which should be read
  @param length          The length (in bytes) of the value in nthe string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_time_read_internal(DYNAMIC_COLUMN_VALUE *store_it_here,
                                  uchar *data, size_t length)
{
  if (length != 6 && length != 3)
    goto err;
  if (length == 6)
  {
    /*
      00000!<-hours--><min-><sec-><---microseconds--->
      1123456789012345612345612345678901234567890
      <123456><123456><123456><123456><123456><123456>
    */
    store_it_here->x.time_value.second_part= (data[0] |
                                              (data[1] << 8) |
                                              ((data[2] & 0xf) << 16));
    store_it_here->x.time_value.second= ((data[2] >> 4) |
                                         ((data[3] & 0x3) << 4));
    store_it_here->x.time_value.minute= (data[3] >> 2);
    store_it_here->x.time_value.hour= (((((uint)data[5]) & 0x3 ) << 8) | data[4]);
    store_it_here->x.time_value.neg= ((data[5] & 0x4) ? 1 : 0);
  }
  else
  {
    /*
     !<-hours--><min-><sec->
     11234567890123456123456
    <123456><123456><123456>
   */
    store_it_here->x.time_value.second_part= 0;
    store_it_here->x.time_value.second= (data[0] & 0x3f);
    store_it_here->x.time_value.minute= (data[0] >> 6) | ((data[1] & 0xf) << 2);
    store_it_here->x.time_value.hour= (data[1] >> 4) | ((data[2] & 0x3f) << 4);
    store_it_here->x.time_value.neg= ((data[2] & 0x80) ? 1 : 0);
  }
  if (store_it_here->x.time_value.second > 59 ||
      store_it_here->x.time_value.minute > 59 ||
      store_it_here->x.time_value.hour > 838 ||
      store_it_here->x.time_value.second_part > 999999)
    goto err;
  return ER_DYNCOL_OK;

err:
  store_it_here->x.time_value.time_type= MYSQL_TIMESTAMP_ERROR;
  return ER_DYNCOL_FORMAT;
}


/**
  Append the string with given date value.

  @param str             the string where to put the value
  @param value           the value to put in the string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_date_store(DYNAMIC_COLUMN *str, MYSQL_TIME *value)
{
  uchar *buf;
  if (dynstr_realloc(str, 3))
    return ER_DYNCOL_RESOURCE;

  buf= ((uchar *)str->str) + str->length;
  if (value->time_type == MYSQL_TIMESTAMP_NONE ||
      value->time_type == MYSQL_TIMESTAMP_ERROR ||
      value->time_type == MYSQL_TIMESTAMP_TIME)
    value->year= value->month= value->day = 0;
  DBUG_ASSERT(value->year <= 9999);
  DBUG_ASSERT(value->month <= 12);
  DBUG_ASSERT(value->day <= 31);
  /*
    0<----year----><mn><day>
    012345678901234123412345
    <123456><123456><123456>
  */
  buf[0]= (value->day |
           ((value->month & 0x7) << 5));
  buf[1]= ((value->month >> 3) | ((value->year & 0x7F) << 1));
  buf[2]= (value->year >> 7);
  str->length+= 3;
  return ER_DYNCOL_OK;
}



/**
  Read date value of given length from the packed string

  @param store_it_here   The structure to store the value
  @param data            The packed string which should be read
  @param length          The length (in bytes) of the value in nthe string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_date_read(DYNAMIC_COLUMN_VALUE *store_it_here,
                         uchar *data, size_t length)
{
  store_it_here->x.time_value.neg= 0;
  store_it_here->x.time_value.second_part= 0;
  store_it_here->x.time_value.hour= 0;
  store_it_here->x.time_value.minute= 0;
  store_it_here->x.time_value.second= 0;
  store_it_here->x.time_value.time_type= MYSQL_TIMESTAMP_DATE;
  return dynamic_column_date_read_internal(store_it_here, data, length);
}

/**
  Internal function for reading date part from the string.

  @param store_it_here   The structure to store the value
  @param data            The packed string which should be read
  @param length          The length (in bytes) of the value in nthe string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_date_read_internal(DYNAMIC_COLUMN_VALUE *store_it_here,
                                  uchar *data,
                                  size_t length)
{
  if (length != 3)
    goto err;
  /*
    0<----year----><mn><day>
     12345678901234123412345
    <123456><123456><123456>
  */
  store_it_here->x.time_value.day= (data[0] & 0x1f);
  store_it_here->x.time_value.month= (((data[1] & 0x1) << 3) |
                                    (data[0] >> 5));
  store_it_here->x.time_value.year= ((((uint)data[2]) << 7) |
                                    (data[1] >> 1));
  if (store_it_here->x.time_value.day > 31 ||
      store_it_here->x.time_value.month > 12 ||
      store_it_here->x.time_value.year > 9999)
    goto err;
  return ER_DYNCOL_OK;

err:
  store_it_here->x.time_value.time_type= MYSQL_TIMESTAMP_ERROR;
  return ER_DYNCOL_FORMAT;
}


/**
  Append the string with given value.

  @param str             the string where to put the value
  @param value           the value to put in the string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
data_store(DYNAMIC_COLUMN *str, DYNAMIC_COLUMN_VALUE *value,
           enum enum_dyncol_format format)
{
  switch (value->type) {
  case DYN_COL_INT:
    return dynamic_column_sint_store(str, value->x.long_value);
  case DYN_COL_UINT:
    return dynamic_column_uint_store(str, value->x.ulong_value);
  case DYN_COL_DOUBLE:
    return dynamic_column_double_store(str, value->x.double_value);
  case DYN_COL_STRING:
    return dynamic_column_string_store(str, &value->x.string.value,
                                     value->x.string.charset);
  case DYN_COL_DECIMAL:
    return dynamic_column_decimal_store(str, &value->x.decimal.value);
  case DYN_COL_DATETIME:
    /* date+time in bits: 14 + 4 + 5 + 5 + 6 + 6 40bits = 5 bytes */
    return dynamic_column_date_time_store(str, &value->x.time_value, format);
  case DYN_COL_DATE:
    /* date in dits: 14 + 4 + 5 = 23bits ~= 3bytes*/
    return dynamic_column_date_store(str, &value->x.time_value);
  case DYN_COL_TIME:
    /* time in bits: 5 + 6 + 6 = 17bits ~= 3bytes*/
    return dynamic_column_time_store(str, &value->x.time_value, format);
  case DYN_COL_DYNCOL:
    return dynamic_column_dyncol_store(str, &value->x.string.value);
  case DYN_COL_NULL:
    break;                                      /* Impossible */
  }
  DBUG_ASSERT(0);
  return ER_DYNCOL_OK;                          /* Impossible */
}


/**
  Write information to the fixed header

  @param str             String where to write the header
  @param offset_size     Size of offset field in bytes
  @param column_count    Number of columns
*/

static void set_fixed_header(DYNAMIC_COLUMN *str,
                             uint offset_size,
                             uint column_count)
{
  DBUG_ASSERT(column_count <= 0xffff);
  DBUG_ASSERT(offset_size <= MAX_OFFSET_LENGTH);
  str->str[0]= ((str->str[0] & ~DYNCOL_FLG_OFFSET) |
                (offset_size - 1));             /* size of offset */
  int2store(str->str + 1, column_count);        /* columns number */
  DBUG_ASSERT((str->str[0] & (~DYNCOL_FLG_KNOWN)) == 0);
}

/**
  Adds columns into the empty string

  @param str             String where to write the data (the record)
  @param hdr             Dynamic columns record descriptor
  @param column_count    Number of columns in the arrays
  @param column_keys     Array of columns keys (uint or LEX_STRING)
  @param values          Array of columns values
  @param new_str         True if we need to allocate new string

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_new_column_store(DYNAMIC_COLUMN *str,
                         DYN_HEADER *hdr,
                         uint column_count,
                         void *column_keys,
                         DYNAMIC_COLUMN_VALUE *values,
                         my_bool new_str)
{
  struct st_service_funcs *fmt= fmt_data + hdr->format;
  void **columns_order;
  uchar *element;
  uint i;
  enum enum_dyncol_func_result rc= ER_DYNCOL_RESOURCE;
  size_t all_headers_size;

  if (!(columns_order= malloc(sizeof(void*)*column_count)))
    return ER_DYNCOL_RESOURCE;
  if (new_str || str->str == 0)
  {
    if (column_count)
    {
      if (dynamic_column_init_named(str,
                                    fmt->fixed_hdr +
                                    hdr->header_size +
                                    hdr->nmpool_size +
                                    hdr->data_size +
                                    DYNCOL_SYZERESERVE))
        goto err;
    }
    else
    {
      mariadb_dyncol_init(str);
    }
  }
  else
  {
    str->length= 0;
    if (dynstr_realloc(str,
                       fmt->fixed_hdr +
                       hdr->header_size +
                       hdr->nmpool_size +
                       hdr->data_size +
                       DYNCOL_SYZERESERVE))
      goto err;
  }
  if (!column_count)
    return ER_DYNCOL_OK;

  bzero(str->str, fmt->fixed_hdr);
  str->length= fmt->fixed_hdr;

  /* sort columns for the header */
  for (i= 0, element= (uchar *) column_keys;
       i < column_count;
       i++, element+= fmt->key_size_in_array)
    columns_order[i]= (void *)element;
  qsort(columns_order, (size_t)column_count, sizeof(void*), fmt->column_sort);

  /*
    For now we don't allow creating two columns with the same number
    at the time of create.  This can be fixed later to just use the later
    by comparing the pointers.
  */
  for (i= 0; i < column_count - 1; i++)
  {
    if ((*fmt->check_limit)(&columns_order[i]) ||
        (*fmt->column_sort)(&columns_order[i], &columns_order[i + 1]) == 0)
    {
      rc= ER_DYNCOL_DATA;
      goto err;
    }
  }
  if ((*fmt->check_limit)(&columns_order[i]))
  {
    rc= ER_DYNCOL_DATA;
    goto err;
  }

  (*fmt->set_fixed_hdr)(str, hdr);
  /* reserve place for header and name pool */
  str->length+= hdr->header_size + hdr->nmpool_size;

  hdr->entry= hdr->header;
  hdr->name= hdr->nmpool;
  all_headers_size= fmt->fixed_hdr + hdr->header_size + hdr->nmpool_size;
  for (i= 0; i < column_count; i++)
  {
    uint ord= (uint)(((uchar*)columns_order[i] - (uchar*)column_keys) /
                     fmt->key_size_in_array);
    if (values[ord].type != DYN_COL_NULL)
    {
      /* Store header first in the str */
      if ((*fmt->put_header_entry)(hdr, columns_order[i], values + ord,
                                   str->length - all_headers_size))
      {
        rc= ER_DYNCOL_FORMAT;
        goto err;
      }

      /* Store value in 'str + str->length' and increase str->length */
      if ((rc= data_store(str, values + ord, hdr->format)))
        goto err;
    }
  }
  rc= ER_DYNCOL_OK;
err:
  free(columns_order);
  return rc;
}

/**
  Calculate size of header, name pool and data pool

  @param hdr             descriptor of dynamic column record
  @param column_count    number of elements in arrays
  @param column_count    Number of columns in the arrays
  @param column_keys     Array of columns keys (uint or LEX_STRING)
  @param values          Array of columns values

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
calc_var_sizes(DYN_HEADER *hdr,
               uint column_count,
               void *column_keys,
               DYNAMIC_COLUMN_VALUE *values)
{
  struct st_service_funcs *fmt= fmt_data + hdr->format;
  uint i;
  hdr->nmpool_size= hdr->data_size= 0;
  hdr->column_count= 0;
  for (i= 0; i < column_count; i++)
  {
    if (values[i].type != DYN_COL_NULL)
    {
      size_t tmp;
      hdr->column_count++;
      hdr->data_size+= (tmp= dynamic_column_value_len(values + i,
                        hdr->format));
      if (tmp == (size_t) ~0)
        return ER_DYNCOL_DATA;
      hdr->nmpool_size+= (*fmt->name_size)(column_keys, i);
    }
  }
  /*
    We can handle data up to 0x1fffffff (old format) and
    0xfffffffff (new format) bytes now.
  */
  if ((hdr->offset_size= fmt->dynamic_column_offset_bytes(hdr->data_size)) >=
      fmt->max_offset_size)
    return ER_DYNCOL_LIMIT;

  /* header entry is column number or string pointer + offset & type */
  hdr->entry_size= fmt->fixed_hdr_entry + hdr->offset_size;
  hdr->header_size= hdr->column_count * hdr->entry_size;
  return ER_DYNCOL_OK;
}

/**
  Create packed string which contains given columns (internal multi format)

  @param str             String where to write the data
  @param column_count    Number of columns in the arrays
  @param column_keys     Array of columns keys (format dependent)
  @param values          Array of columns values
  @param new_str         True if we need allocate new string
  @param string_keys     keys are strings

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_create_many_internal_fmt(DYNAMIC_COLUMN *str,
                                        uint column_count,
                                        void *column_keys,
                                        DYNAMIC_COLUMN_VALUE *values,
                                        my_bool new_str,
                                        my_bool string_keys)
{
  DYN_HEADER header;
  enum enum_dyncol_func_result rc;
  bzero(&header, sizeof(header));
  header.format= (string_keys ? 1 : 0);

  if (new_str)
  {
    /* to make dynstr_free() working in case of errors */
    mariadb_dyncol_init(str);
  }

  if ((rc= calc_var_sizes(&header, column_count, column_keys, values)) < 0)
    return rc;

  return dynamic_new_column_store(str, &header,
                                  column_count,
                                  column_keys, values,
                                  new_str);
}


/**
  Create packed string which contains given columns

  @param str             String where to write the data
  @param column_count    Number of columns in the arrays
  @param column_numbers  Array of columns numbers
  @param values          Array of columns values

  @return ER_DYNCOL_* return code
*/

enum enum_dyncol_func_result
dynamic_column_create_many(DYNAMIC_COLUMN *str,
                           uint column_count,
                           uint *column_numbers,
                           DYNAMIC_COLUMN_VALUE *values)
{
  DBUG_ENTER("dynamic_column_create_many");
  DBUG_RETURN(dynamic_column_create_many_internal_fmt(str, column_count,
                                                      column_numbers, values,
                                                      TRUE, FALSE));
}

/**
  Create packed string which contains given columns

  @param str             String where to write the data
  @param column_count    Number of columns in the arrays
  @param column_numbers  Array of columns numbers
  @param values          Array of columns values
  @param new_string      True if we need allocate new string

  @return ER_DYNCOL_* return code
*/

enum enum_dyncol_func_result
mariadb_dyncol_create_many_num(DYNAMIC_COLUMN *str,
                               uint column_count,
                               uint *column_numbers,
                               DYNAMIC_COLUMN_VALUE *values,
                               my_bool new_string)
{
  DBUG_ENTER("mariadb_dyncol_create_many_num");
  DBUG_RETURN(dynamic_column_create_many_internal_fmt(str, column_count,
                                                      column_numbers, values,
                                                      new_string, FALSE));
}

/**
  Create packed string which contains given columns

  @param str             String where to write the data
  @param column_count    Number of columns in the arrays
  @param column_keys     Array of columns keys
  @param values          Array of columns value
  @param new_string      True if we need allocate new string

  @return ER_DYNCOL_* return code
*/

enum enum_dyncol_func_result
mariadb_dyncol_create_many_named(DYNAMIC_COLUMN *str,
                                 uint column_count,
                                 LEX_STRING *column_keys,
                                 DYNAMIC_COLUMN_VALUE *values,
                                 my_bool new_string)
{
  DBUG_ENTER("mariadb_dyncol_create_many_named");
  DBUG_RETURN(dynamic_column_create_many_internal_fmt(str, column_count,
                                                      column_keys, values,
                                                      new_string, TRUE));
}

/**
  Create packed string which contains given column

  @param str             String where to write the data
  @param column_number   Column number
  @param value           The columns value

  @return ER_DYNCOL_* return code
*/

enum enum_dyncol_func_result
dynamic_column_create(DYNAMIC_COLUMN *str, uint column_nr,
                      DYNAMIC_COLUMN_VALUE *value)
{
  DBUG_ENTER("dynamic_column_create");
  DBUG_RETURN(dynamic_column_create_many(str, 1, &column_nr, value));
}


/**
  Calculate length of data between given two header entries

  @param entry           Pointer to the first entry
  @param entry_next      Pointer to the last entry
  @param header_end      Pointer to the header end
  @param offset_size     Size of offset field in bytes
  @param last_offset     Size of the data segment

  @return number of bytes
*/

static size_t get_length_interval(uchar *entry, uchar *entry_next,
                                  uchar *header_end, size_t offset_size,
                                  size_t last_offset)
{
  size_t offset, offset_next;
  DYNAMIC_COLUMN_TYPE type, type_next;
  DBUG_ASSERT(entry < entry_next);

  if (type_and_offset_read_num(&type, &offset, entry + COLUMN_NUMBER_SIZE,
                               offset_size))
      return DYNCOL_OFFSET_ERROR;
  if (entry_next >= header_end)
    return (last_offset - offset);
  if (type_and_offset_read_num(&type_next, &offset_next,
                               entry_next + COLUMN_NUMBER_SIZE, offset_size) ||
      (offset_next > last_offset))
    return DYNCOL_OFFSET_ERROR;
  return (offset_next - offset);
}


/**
  Calculate length of data between given hdr->entry and next_entry

  @param hdr             descriptor of dynamic column record
  @param next_entry      next header entry (can point just after last header
                         entry)

  @return number of bytes
*/

static size_t hdr_interval_length(DYN_HEADER *hdr, uchar *next_entry)
{
  struct st_service_funcs *fmt= fmt_data + hdr->format;
  size_t next_entry_offset;
  DYNAMIC_COLUMN_TYPE next_entry_type;
  DBUG_ASSERT(hdr->entry < next_entry);
  DBUG_ASSERT(hdr->entry >= hdr->header);
  DBUG_ASSERT(next_entry <= hdr->header + hdr->header_size);

  if ((*fmt->type_and_offset_read)(&hdr->type, &hdr->offset,
                                   hdr->entry + fmt->fixed_hdr_entry,
                                   hdr->offset_size) ||
      hdr->data_size < hdr->offset)
    return DYNCOL_OFFSET_ERROR;
  if (next_entry == hdr->header + hdr->header_size)
    return hdr->data_size - hdr->offset;
  if ((*fmt->type_and_offset_read)(&next_entry_type, &next_entry_offset,
                                   next_entry + fmt->fixed_hdr_entry,
                                   hdr->offset_size) ||
      hdr->data_size < next_entry_offset)
    return DYNCOL_OFFSET_ERROR;
  return (next_entry_offset - hdr->offset);
}


/**
  Comparator function for references to header entries for qsort
*/

static int header_compar_num(const void *a, const void *b)
{
  uint va= uint2korr((uchar*)a), vb= uint2korr((uchar*)b);
  return (va > vb ? 1 : (va < vb ? -1 : 0));
}


/**
  Find entry in the numeric format header by the column number

  @param hdr             descriptor of dynamic column record
  @param key             number to find

  @return pointer to the entry or NULL
*/

static uchar *find_entry_num(DYN_HEADER *hdr, uint key)
{
  uchar header_entry[2+4];
  DBUG_ASSERT(hdr->format == dyncol_fmt_num);
  int2store(header_entry, key);
  return hdr->entry= bsearch(header_entry, hdr->header,
                             (size_t)hdr->column_count,
                             hdr->entry_size, &header_compar_num);
}


/**
  Read name from header entry

  @param hdr             descriptor of dynamic column record
  @param entry           pointer to the header entry
  @param name            where to put name

  @return 0 ok
  @return 1 error in data
*/

static my_bool read_name(DYN_HEADER *hdr, uchar *entry, LEX_STRING *name)
{
  size_t nmoffset= uint2korr(entry);
  uchar *next_entry= entry + hdr->entry_size;

  if (nmoffset > hdr->nmpool_size)
    return 1;

  name->str= (char *)hdr->nmpool + nmoffset;
  if (next_entry == hdr->header + hdr->header_size)
    name->length= hdr->nmpool_size - nmoffset;
  else
  {
    size_t next_nmoffset= uint2korr(next_entry);
    if (next_nmoffset > hdr->nmpool_size)
      return 1;
    name->length= next_nmoffset - nmoffset;
  }
  return 0;
}


/**
  Find entry in the names format header by the column number

  @param hdr             descriptor of dynamic column record
  @param key             name to find

  @return pointer to the entry or NULL
*/
static uchar *find_entry_named(DYN_HEADER *hdr, LEX_STRING *key)
{
  uchar *min= hdr->header;
  uchar *max= hdr->header + (hdr->column_count - 1) * hdr->entry_size;
  uchar *mid;
  DBUG_ASSERT(hdr->format == dyncol_fmt_str);
  DBUG_ASSERT(hdr->nmpool != NULL);
  while (max >= min)
  {
    LEX_STRING name;
    int cmp;
    mid= hdr->header + ((min - hdr->header) +
                        (max - hdr->header)) /
      2 /
      hdr->entry_size * hdr->entry_size;
    if (read_name(hdr, mid, &name))
      return NULL;
    cmp= mariadb_dyncol_column_cmp_named(&name, key);
    if (cmp < 0)
      min= mid + hdr->entry_size;
    else if (cmp > 0)
      max= mid - hdr->entry_size;
    else
      return mid;
  }
  return NULL;
}


/**
  Write number in the buffer (backward direction - starts from the buffer end)

  @return pointer on the number begining
*/

static char *backwritenum(char *chr, uint numkey)
{
  if (numkey == 0)
    *(--chr)= '0';
  else
    while (numkey > 0)
    {
      *(--chr)= '0' + numkey % 10;
      numkey/= 10;
    }
  return chr;
}


/**
  Find column and fill information about it

  @param hdr             descriptor of dynamic column record
  @param numkey          Number of the column to fetch (if strkey is NULL)
  @param strkey          Name of the column to fetch (or NULL)

  @return 0 ok
  @return 1 error in data
*/

static my_bool
find_column(DYN_HEADER *hdr, uint numkey, LEX_STRING *strkey)
{
  LEX_STRING nmkey;
  char nmkeybuff[DYNCOL_NUM_CHAR]; /* to fit max 2 bytes number */
  DBUG_ASSERT(hdr->header != NULL);

  if (hdr->header + hdr->header_size > hdr->data_end)
    return TRUE;

  /* fix key */
  if (hdr->format == dyncol_fmt_num && strkey != NULL)
  {
    char *end;
    numkey= (uint) strtoul(strkey->str, &end, 10);
    if (end != strkey->str + strkey->length)
    {
      /* we can't find non-numeric key among numeric ones */
      hdr->type= DYN_COL_NULL;
      return 0;
    }
  }
  else if (hdr->format == dyncol_fmt_str && strkey == NULL)
  {
    nmkey.str= backwritenum(nmkeybuff + sizeof(nmkeybuff), numkey);
    nmkey.length= (nmkeybuff + sizeof(nmkeybuff)) - nmkey.str;
    strkey= &nmkey;
  }
  if (hdr->format == dyncol_fmt_num)
    hdr->entry= find_entry_num(hdr, numkey);
  else
    hdr->entry= find_entry_named(hdr, strkey);

  if (!hdr->entry)
  {
    /* Column not found */
    hdr->type= DYN_COL_NULL;
    return 0;
  }
  hdr->length= hdr_interval_length(hdr, hdr->entry + hdr->entry_size);
  hdr->data= hdr->dtpool + hdr->offset;
  /*
    Check that the found data is withing the ranges. This can happen if
    we get data with wrong offsets.
  */
  if (hdr->length == DYNCOL_OFFSET_ERROR ||
      hdr->length > INT_MAX || hdr->offset > hdr->data_size)
    return 1;

  return 0;
}


/**
  Read and check the header of the dynamic string

  @param hdr             descriptor of dynamic column record
  @param str             Dynamic string

  @retval FALSE OK
  @retval TRUE  error

  Note
    We don't check for str->length == 0 as all code that calls this
    already have handled this case.
*/

static inline my_bool read_fixed_header(DYN_HEADER *hdr,
                                        DYNAMIC_COLUMN *str)
{
  DBUG_ASSERT(str != NULL && str->length != 0);
  if ((str->length < 1)  ||
      (str->str[0] & (~DYNCOL_FLG_KNOWN)))
    return 1;
  hdr->format= ((str->str[0] & DYNCOL_FLG_NAMES) ?
                dyncol_fmt_str:
                dyncol_fmt_num);
  if ((str->length < fmt_data[hdr->format].fixed_hdr))
    return 1;                                   /* Wrong header */
  hdr->offset_size= (str->str[0] & DYNCOL_FLG_OFFSET) + 1 +
    (hdr->format == dyncol_fmt_str ? 1 : 0);
  hdr->column_count= uint2korr(str->str + 1);
  if (hdr->format == dyncol_fmt_str)
    hdr->nmpool_size= uint2korr(str->str + 3); // only 2 bytes supported for now
  else
    hdr->nmpool_size= 0;
  return 0;
}


/**
  Get dynamic column value by column number

  @param str             The packed string to extract the column
  @param column_nr       Number of column to fetch
  @param store_it_here   Where to store the extracted value

  @return ER_DYNCOL_* return code
*/

enum enum_dyncol_func_result
dynamic_column_get(DYNAMIC_COLUMN *str, uint column_nr,
                       DYNAMIC_COLUMN_VALUE *store_it_here)
{
  return dynamic_column_get_internal(str, store_it_here, column_nr, NULL);
}

enum enum_dyncol_func_result
mariadb_dyncol_get_num(DYNAMIC_COLUMN *str, uint column_nr,
                       DYNAMIC_COLUMN_VALUE *store_it_here)
{
  return dynamic_column_get_internal(str, store_it_here, column_nr, NULL);
}


/**
  Get dynamic column value by name

  @param str             The packed string to extract the column
  @param name            Name of column to fetch
  @param store_it_here   Where to store the extracted value

  @return ER_DYNCOL_* return code
*/

enum enum_dyncol_func_result
mariadb_dyncol_get_named(DYNAMIC_COLUMN *str, LEX_STRING *name,
                         DYNAMIC_COLUMN_VALUE *store_it_here)
{
  DBUG_ASSERT(name != NULL);
  return dynamic_column_get_internal(str, store_it_here, 0, name);
}


static enum enum_dyncol_func_result
dynamic_column_get_value(DYN_HEADER *hdr, DYNAMIC_COLUMN_VALUE *store_it_here)
{
  static enum enum_dyncol_func_result rc;
  switch ((store_it_here->type= hdr->type)) {
  case DYN_COL_INT:
    rc= dynamic_column_sint_read(store_it_here, hdr->data, hdr->length);
    break;
  case DYN_COL_UINT:
    rc= dynamic_column_uint_read(store_it_here, hdr->data, hdr->length);
    break;
  case DYN_COL_DOUBLE:
    rc= dynamic_column_double_read(store_it_here, hdr->data, hdr->length);
    break;
  case DYN_COL_STRING:
    rc= dynamic_column_string_read(store_it_here, hdr->data, hdr->length);
    break;
  case DYN_COL_DECIMAL:
    rc= dynamic_column_decimal_read(store_it_here, hdr->data, hdr->length);
    break;
  case DYN_COL_DATETIME:
    rc= dynamic_column_date_time_read(store_it_here, hdr->data,
                                      hdr->length);
    break;
  case DYN_COL_DATE:
    rc= dynamic_column_date_read(store_it_here, hdr->data, hdr->length);
    break;
  case DYN_COL_TIME:
    rc= dynamic_column_time_read(store_it_here, hdr->data, hdr->length);
    break;
  case DYN_COL_NULL:
    rc= ER_DYNCOL_OK;
    break;
  case DYN_COL_DYNCOL:
    rc= dynamic_column_dyncol_read(store_it_here, hdr->data, hdr->length);
    break;
  default:
    rc= ER_DYNCOL_FORMAT;
    store_it_here->type= DYN_COL_NULL;
    break;
  }
  return rc;
}

/**
  Get dynamic column value by number or name

  @param str             The packed string to extract the column
  @param store_it_here   Where to store the extracted value
  @param numkey          Number of the column to fetch (if strkey is NULL)
  @param strkey          Name of the column to fetch (or NULL)

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_get_internal(DYNAMIC_COLUMN *str,
                            DYNAMIC_COLUMN_VALUE *store_it_here,
                            uint num_key, LEX_STRING *str_key)
{
  DYN_HEADER header;
  enum enum_dyncol_func_result rc= ER_DYNCOL_FORMAT;
  bzero(&header, sizeof(header));

  if (str->length == 0)
    goto null;

  if ((rc= init_read_hdr(&header, str)) < 0)
    goto err;

  if (header.column_count == 0)
    goto null;

  if (find_column(&header, num_key, str_key))
    goto err;

  rc= dynamic_column_get_value(&header, store_it_here);
  return rc;

null:
    rc= ER_DYNCOL_OK;
err:
    store_it_here->type= DYN_COL_NULL;
    return rc;
}


/**
  Check existence of the column in the packed string (by number)

  @param str             The packed string to check the column
  @param column_nr       Number of column to check

  @return ER_DYNCOL_* return code
*/

enum enum_dyncol_func_result
dynamic_column_exists(DYNAMIC_COLUMN *str, uint column_nr)
{
  return dynamic_column_exists_internal(str, column_nr, NULL);
}

enum enum_dyncol_func_result
mariadb_dyncol_exists_num(DYNAMIC_COLUMN *str, uint column_nr)
{
  return dynamic_column_exists_internal(str, column_nr, NULL);
}

/**
  Check existence of the column in the packed string (by name)

  @param str             The packed string to check the column
  @param name            Name of column to check

  @return ER_DYNCOL_* return code
*/

enum enum_dyncol_func_result
mariadb_dyncol_exists_named(DYNAMIC_COLUMN *str, LEX_STRING *name)
{
  DBUG_ASSERT(name != NULL);
  return dynamic_column_exists_internal(str, 0, name);
}


/**
  Check existence of the column in the packed string (by name of number)

  @param str             The packed string to check the column
  @param num_key         Number of the column to fetch (if strkey is NULL)
  @param str_key         Name of the column to fetch (or NULL)

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_exists_internal(DYNAMIC_COLUMN *str, uint num_key,
                               LEX_STRING *str_key)
{
  DYN_HEADER header;
  enum enum_dyncol_func_result rc;
  bzero(&header, sizeof(header));

  if (str->length == 0)
    return ER_DYNCOL_NO;                        /* no columns */

  if ((rc= init_read_hdr(&header, str)) < 0)
    return rc;

  if (header.column_count == 0)
    return ER_DYNCOL_NO;                        /* no columns */

  if (find_column(&header, num_key, str_key))
    return ER_DYNCOL_FORMAT;

  return (header.type != DYN_COL_NULL ? ER_DYNCOL_YES : ER_DYNCOL_NO);
}


/**
  List not-null columns in the packed string (only numeric format)

  @param str             The packed string
  @param array_of_uint   Where to put reference on created array

  @return ER_DYNCOL_* return code
*/
enum enum_dyncol_func_result
dynamic_column_list(DYNAMIC_COLUMN *str, DYNAMIC_ARRAY *array_of_uint)
{
  DYN_HEADER header;
  uchar *read;
  uint i;
  enum enum_dyncol_func_result rc;

  bzero(array_of_uint, sizeof(*array_of_uint)); /* In case of errors */
  if (str->length == 0)
    return ER_DYNCOL_OK;                        /* no columns */

  if ((rc= init_read_hdr(&header, str)) < 0)
    return rc;

  if (header.format != dyncol_fmt_num)
    return ER_DYNCOL_FORMAT;

  if (header.entry_size * header.column_count + FIXED_HEADER_SIZE >
      str->length)
    return ER_DYNCOL_FORMAT;

  if (my_init_dynamic_array(array_of_uint, sizeof(uint), header.column_count,
                            0, MYF(0)))
    return ER_DYNCOL_RESOURCE;

  for (i= 0, read= header.header;
       i < header.column_count;
       i++, read+= header.entry_size)
  {
    uint nm= uint2korr(read);
    /* Insert can't never fail as it's pre-allocated above */
    (void) insert_dynamic(array_of_uint, (uchar *)&nm);
  }
  return ER_DYNCOL_OK;
}

/**
  List not-null columns in the packed string (only numeric format)

  @param str             The packed string
  @param array_of_uint   Where to put reference on created array

  @return ER_DYNCOL_* return code
*/
enum enum_dyncol_func_result
mariadb_dyncol_list_num(DYNAMIC_COLUMN *str, uint *count, uint **nums)
{
  DYN_HEADER header;
  uchar *read;
  uint i;
  enum enum_dyncol_func_result rc;

  (*nums)= 0; (*count)= 0;                      /* In case of errors */

  if (str->length == 0)
    return ER_DYNCOL_OK;                        /* no columns */

  if ((rc= init_read_hdr(&header, str)) < 0)
    return rc;

  if (header.format != dyncol_fmt_num)
    return ER_DYNCOL_FORMAT;

  if (header.entry_size * header.column_count + FIXED_HEADER_SIZE >
      str->length)
    return ER_DYNCOL_FORMAT;

  if (!((*nums)= my_malloc(sizeof(uint) * header.column_count, MYF(0))))
    return ER_DYNCOL_RESOURCE;

  for (i= 0, read= header.header;
       i < header.column_count;
       i++, read+= header.entry_size)
  {
    (*nums)[i]= uint2korr(read);
  }
  (*count)= header.column_count;
  return ER_DYNCOL_OK;
}

/**
  List not-null columns in the packed string (any format)

  @param str             The packed string
  @param count           Number of names in the list
  @param names           Where to put names list (should be freed)

  @return ER_DYNCOL_* return code
*/

enum enum_dyncol_func_result
mariadb_dyncol_list_named(DYNAMIC_COLUMN *str, uint *count, LEX_STRING **names)
{
  DYN_HEADER header;
  uchar *read;
  char *pool;
  struct st_service_funcs *fmt;
  uint i;
  enum enum_dyncol_func_result rc;

  (*names)= 0; (*count)= 0;

  if (str->length == 0)
    return ER_DYNCOL_OK;                        /* no columns */

  if ((rc= init_read_hdr(&header, str)) < 0)
    return rc;

  fmt= fmt_data + header.format;

  if (header.entry_size * header.column_count + fmt->fixed_hdr >
      str->length)
    return ER_DYNCOL_FORMAT;

  if (header.format == dyncol_fmt_num)
    *names= my_malloc(sizeof(LEX_STRING) * header.column_count +
                      DYNCOL_NUM_CHAR * header.column_count, MYF(0));
  else
    *names= my_malloc(sizeof(LEX_STRING) * header.column_count +
                      header.nmpool_size + header.column_count, MYF(0));
  if (!(*names))
    return ER_DYNCOL_RESOURCE;
  pool= ((char *)(*names)) + sizeof(LEX_STRING) * header.column_count;

  for (i= 0, read= header.header;
       i < header.column_count;
       i++, read+= header.entry_size)
  {
    if (header.format == dyncol_fmt_num)
    {
      uint nm= uint2korr(read);
      (*names)[i].str= pool;
      pool+= DYNCOL_NUM_CHAR;
      (*names)[i].length=
        longlong2str(nm, (*names)[i].str, 10) - (*names)[i].str;
    }
    else
    {
      LEX_STRING tmp;
      if (read_name(&header, read, &tmp))
        return ER_DYNCOL_FORMAT;
      (*names)[i].length= tmp.length;
      (*names)[i].str= pool;
      pool+= tmp.length + 1;
      memcpy((*names)[i].str, (const void *)tmp.str, tmp.length);
      (*names)[i].str[tmp.length]= '\0'; // just for safety
    }
  }
  (*count)= header.column_count;
  return ER_DYNCOL_OK;
}

/**
  Find the place of the column in the header or place where it should be put

  @param hdr             descriptor of dynamic column record
  @param key             Name or number of column to fetch
                         (depends on string_key)
  @param string_key      True if we gave pointer to LEX_STRING.

  @retval TRUE found
  @retval FALSE pointer set to the next row
*/

static my_bool
find_place(DYN_HEADER *hdr, void *key, my_bool string_keys)
{
  uint mid, start, end, val;
  int UNINIT_VAR(flag);
  LEX_STRING str;
  char buff[DYNCOL_NUM_CHAR];
  my_bool need_conversion= ((string_keys ? dyncol_fmt_str : dyncol_fmt_num) !=
                            hdr->format);
  /* new format can't be numeric if the old one is names */
  DBUG_ASSERT(string_keys ||
              hdr->format == dyncol_fmt_num);

  start= 0;
  end= hdr->column_count -1;
  mid= 1;
  while (start != end)
  {
    uint val;
    mid= (start + end) / 2;
    hdr->entry= hdr->header + mid * hdr->entry_size;
    if (!string_keys)
    {
      val= uint2korr(hdr->entry);
      flag= CMP_NUM(*((uint *)key), val);
    }
    else
    {
      if (need_conversion)
      {
        str.str= backwritenum(buff + sizeof(buff), uint2korr(hdr->entry));
        str.length= (buff + sizeof(buff)) - str.str;
      }
      else
      {
        DBUG_ASSERT(hdr->format == dyncol_fmt_str);
        if (read_name(hdr, hdr->entry, &str))
          return 0;
      }
      flag= mariadb_dyncol_column_cmp_named((LEX_STRING *)key, &str);
    }
    if (flag <= 0)
      end= mid;
    else
      start= mid + 1;
  }
  hdr->entry= hdr->header + start * hdr->entry_size;
  if (start != mid)
  {
    if (!string_keys)
    {
      val= uint2korr(hdr->entry);
      flag= CMP_NUM(*((uint *)key), val);
    }
    else
    {
      if (need_conversion)
      {
        str.str= backwritenum(buff + sizeof(buff), uint2korr(hdr->entry));
        str.length= (buff + sizeof(buff)) - str.str;
      }
      else
      {
        DBUG_ASSERT(hdr->format == dyncol_fmt_str);
        if (read_name(hdr, hdr->entry, &str))
          return 0;
      }
      flag= mariadb_dyncol_column_cmp_named((LEX_STRING *)key, &str);
    }
  }
  if (flag > 0)
    hdr->entry+= hdr->entry_size; /* Point at next bigger key */
  return flag == 0;
}


/*
  It is internal structure which describes a plan of changing the record
  of dynamic columns
*/

typedef enum {PLAN_REPLACE, PLAN_ADD, PLAN_DELETE, PLAN_NOP} PLAN_ACT;

struct st_plan {
  DYNAMIC_COLUMN_VALUE *val;
  void *key;
  uchar *place;
  size_t length;
  long long hdelta, ddelta, ndelta;
  long long mv_offset, mv_length;
  uint mv_end;
  PLAN_ACT act;
};
typedef struct st_plan PLAN;


/**
  Sort function for plan by column number
*/

static int plan_sort_num(const void *a, const void *b)
{
  return *((uint *)((PLAN *)a)->key) - *((uint *)((PLAN *)b)->key);
}


/**
  Sort function for plan by column name
*/

static int plan_sort_named(const void *a, const void *b)
{
  return mariadb_dyncol_column_cmp_named((LEX_STRING *)((PLAN *)a)->key,
                                         (LEX_STRING *)((PLAN *)b)->key);
}

#define DELTA_CHECK(S, D, C)        \
  if ((S) == 0)                     \
    (S)= (D);                       \
  else if (((S) > 0 && (D) < 0) ||  \
            ((S) < 0 && (D) > 0))   \
  {                                 \
    (C)= TRUE;                      \
  }

/**
  Update dynamic column by copying in a new record (string).

  @param str             Dynamic column record to change
  @param plan            Plan of changing the record
  @param add_column_count number of records in the plan array.
  @param hdr             descriptor of old dynamic column record
  @param new_hdr         descriptor of new dynamic column record
  @param convert         need conversion from numeric to names format

  @return ER_DYNCOL_* return code
*/

static enum enum_dyncol_func_result
dynamic_column_update_copy(DYNAMIC_COLUMN *str, PLAN *plan,
                           uint add_column_count,
                           DYN_HEADER *hdr, DYN_HEADER *new_hdr,
                           my_bool convert)
{
  DYNAMIC_COLUMN tmp;
  struct st_service_funcs *fmt= fmt_data + hdr->format,
                          *new_fmt= fmt_data + new_hdr->format;
  uint i, j, k;
  size_t all_headers_size;

  if (dynamic_column_init_named(&tmp,
                              (new_fmt->fixed_hdr + new_hdr->header_size +
                               new_hdr->nmpool_size +
                               new_hdr->data_size + DYNCOL_SYZERESERVE)))
  {
    return ER_DYNCOL_RESOURCE;
  }
  bzero(tmp.str, new_fmt->fixed_hdr);
  (*new_fmt->set_fixed_hdr)(&tmp, new_hdr);
  /* Adjust tmp to contain whole the future header */
  tmp.length= new_fmt->fixed_hdr + new_hdr->header_size + new_hdr->nmpool_size;


  /*
    Copy data to the new string
    i= index in array of changes
    j= index in packed string header index
  */
  new_hdr->entry= new_hdr->header;
  new_hdr->name= new_hdr->nmpool;
  all_headers_size= new_fmt->fixed_hdr +
    new_hdr->header_size + new_hdr->nmpool_size;
  for (i= 0, j= 0; i < add_column_count || j < hdr->column_count; i++)
  {
    size_t UNINIT_VAR(first_offset);
    uint start= j, end;

    /*
      Search in i and j for the next column to add from i and where to
      add.
    */

    while (i < add_column_count && plan[i].act == PLAN_NOP)
      i++;                                    /* skip NOP */

    if (i == add_column_count)
      j= end= hdr->column_count;
    else
    {
      /*
        old data portion. We don't need to check that j < column_count
        as plan[i].place is guaranteed to have a pointer inside the
        data.
      */
      while (hdr->header + j * hdr->entry_size < plan[i].place)
        j++;
      end= j;
      if ((plan[i].act == PLAN_REPLACE || plan[i].act == PLAN_DELETE))
        j++;                              /* data at 'j' will be removed */
    }

    /*
      Adjust all headers since last loop.
      We have to do this as the offset for data has moved
    */
    for (k= start; k < end; k++)
    {
      uchar *read= hdr->header + k * hdr->entry_size;
      void *key;
      LEX_STRING name;
      size_t offs;
      uint nm;
      DYNAMIC_COLUMN_TYPE tp;
      char buff[DYNCOL_NUM_CHAR];

      if (hdr->format == dyncol_fmt_num)
      {
        if (convert)
        {
          name.str= backwritenum(buff + sizeof(buff), uint2korr(read));
          name.length= (buff + sizeof(buff)) - name.str;
          key= &name;
        }
        else
        {
          nm= uint2korr(read);                    /* Column nummber */
          key= &nm;
        }
      }
      else
      {
        if (read_name(hdr, read, &name))
          goto err;
        key= &name;
      }
      if (fmt->type_and_offset_read(&tp, &offs,
                                    read + fmt->fixed_hdr_entry,
                                    hdr->offset_size))
          goto err;
      if (k == start)
        first_offset= offs;
      else if (offs < first_offset)
        goto err;

      offs+= plan[i].ddelta;
      {
        DYNAMIC_COLUMN_VALUE val;
        val.type= tp; // only the type used in the header
        if ((*new_fmt->put_header_entry)(new_hdr, key, &val, offs))
          goto err;
      }
    }

    /* copy first the data that was not replaced in original packed data */
    if (start < end)
    {
      size_t data_size;
      /* Add old data last in 'tmp' */
      hdr->entry= hdr->header + start * hdr->entry_size;
      data_size=
        hdr_interval_length(hdr, hdr->header + end * hdr->entry_size);
      if (data_size == DYNCOL_OFFSET_ERROR ||
          (long) data_size < 0 ||
          data_size > hdr->data_size - first_offset)
        goto err;

      memcpy(tmp.str + tmp.length, (char *)hdr->dtpool + first_offset,
             data_size);
      tmp.length+= data_size;
    }

    /* new data adding */
    if (i < add_column_count)
    {
      if( plan[i].act == PLAN_ADD || plan[i].act == PLAN_REPLACE)
      {
        if ((*new_fmt->put_header_entry)(new_hdr, plan[i].key,
                                         plan[i].val,
                                         tmp.length - all_headers_size))
          goto err;
        data_store(&tmp, plan[i].val, new_hdr->format); /* Append new data */
      }
    }
  }
  mariadb_dyncol_free(str);
  *str= tmp;
  return ER_DYNCOL_OK;
err:
  mariadb_dyncol_free(&tmp);
  return ER_DYNCOL_FORMAT;
}

static enum enum_dyncol_func_result
dynamic_column_update_move_left(DYNAMIC_COLUMN *str, PLAN *plan,
                                size_t offset_size,
                                size_t entry_size,
                                size_t header_size,
                                size_t new_offset_size,
                                size_t new_entry_size,
                                size_t new_header_size,
                                uint column_count,
                                uint new_column_count,
                                uint add_column_count,
                                uchar *header_end,
                                size_t max_offset)
{
  uchar *write;
  uchar *header_base= (uchar *)str->str + FIXED_HEADER_SIZE;
  uint i, j, k;
  size_t curr_offset;

  write= (uchar *)str->str + FIXED_HEADER_SIZE;
  set_fixed_header(str, (uint)new_offset_size, new_column_count);

  /*
    Move headers first.
    i= index in array of changes
    j= index in packed string header index
  */
  for (curr_offset= 0, i= 0, j= 0;
       i < add_column_count || j < column_count;
       i++)
  {
    size_t UNINIT_VAR(first_offset);
    uint start= j, end;

    /*
      Search in i and j for the next column to add from i and where to
      add.
    */

    while (i < add_column_count && plan[i].act == PLAN_NOP)
      i++;                                    /* skip NOP */

    if (i == add_column_count)
      j= end= column_count;
    else
    {
      /*
        old data portion. We don't need to check that j < column_count
        as plan[i].place is guaranteed to have a pointer inside the
        data.
      */
      while (header_base + j * entry_size < plan[i].place)
        j++;
      end= j;
      if ((plan[i].act == PLAN_REPLACE || plan[i].act == PLAN_DELETE))
        j++;                              /* data at 'j' will be removed */
    }
    plan[i].mv_end= end;

    {
      DYNAMIC_COLUMN_TYPE tp;
      if (type_and_offset_read_num(&tp, &first_offset,
                                   header_base + start * entry_size +
                                   COLUMN_NUMBER_SIZE, offset_size))
        return ER_DYNCOL_FORMAT;
    }
    /* find data to be moved */
    if (start < end)
    {
      size_t data_size=
        get_length_interval(header_base + start * entry_size,
                            header_base + end * entry_size,
                            header_end, offset_size, max_offset);
      if (data_size == DYNCOL_OFFSET_ERROR ||
          (long) data_size < 0 ||
          data_size > max_offset - first_offset)
      {
        str->length= 0; // just something valid
        return ER_DYNCOL_FORMAT;
      }
      DBUG_ASSERT(curr_offset == first_offset + plan[i].ddelta);
      plan[i].mv_offset= first_offset;
      plan[i].mv_length= data_size;
      curr_offset+= data_size;
    }
    else
    {
      plan[i].mv_length= 0;
      plan[i].mv_offset= curr_offset;
    }

    if (plan[i].ddelta == 0 && offset_size == new_offset_size &&
        plan[i].act != PLAN_DELETE)
      write+= entry_size * (end - start);
    else
    {
      /*
        Adjust all headers since last loop.
        We have to do this as the offset for data has moved
      */
      for (k= start; k < end; k++)
      {
        uchar *read= header_base + k * entry_size;
        size_t offs;
        uint nm;
        DYNAMIC_COLUMN_TYPE tp;

        nm= uint2korr(read);                    /* Column nummber */
        if (type_and_offset_read_num(&tp, &offs, read + COLUMN_NUMBER_SIZE,
                                     offset_size))
          return ER_DYNCOL_FORMAT;

        if (k > start && offs < first_offset)
        {
          str->length= 0; // just something valid
          return ER_DYNCOL_FORMAT;
        }

        offs+= plan[i].ddelta;
        int2store(write, nm);
        /* write rest of data at write + COLUMN_NUMBER_SIZE */
        type_and_offset_store_num(write, new_offset_size, tp, offs);
        write+= new_entry_size;
      }
    }

    /* new data adding */
    if (i < add_column_count)
    {
      if( plan[i].act == PLAN_ADD || plan[i].act == PLAN_REPLACE)
      {
        int2store(write, *((uint *)plan[i].key));
        type_and_offset_store_num(write, new_offset_size,
                                  plan[i].val[0].type,
                                  curr_offset);
        write+= new_entry_size;
        curr_offset+= plan[i].length;
      }
    }
  }

  /*
    Move data.
    i= index in array of changes
    j= index in packed string header index
  */
  str->length= (FIXED_HEADER_SIZE + new_header_size);
  for (i= 0, j= 0;
       i < add_column_count || j < column_count;
       i++)
  {
    uint start= j, end;

    /*
      Search in i and j for the next column to add from i and where to
      add.
    */

    while (i < add_column_count && plan[i].act == PLAN_NOP)
      i++;                                    /* skip NOP */

    j= end= plan[i].mv_end;
    if (i != add_column_count &&
        (plan[i].act == PLAN_REPLACE || plan[i].act == PLAN_DELETE))
      j++;

    /* copy first the data that was not replaced in original packed data */
    if (start < end && plan[i].mv_length)
    {
      memmove((header_base + new_header_size +
               plan[i].mv_offset + plan[i].ddelta),
              header_base + header_size + plan[i].mv_offset,
              plan[i].mv_length);
    }
    str->length+= plan[i].mv_length;

    /* new data adding */
    if (i < add_column_count)
    {
      if( plan[i].act == PLAN_ADD || plan[i].act == PLAN_REPLACE)
      {
        data_store(str, plan[i].val, dyncol_fmt_num);/* Append new data */
      }
    }
  }
  return ER_DYNCOL_OK;
}

#ifdef UNUSED
static enum enum_dyncol_func_result
dynamic_column_update_move_right(DYNAMIC_COLUMN *str, PLAN *plan,
                                 size_t offset_size,
                                 size_t entry_size,
                                 size_t header_size,
                                 size_t new_offset_size,
                                 size_t new_entry_size,
                                 size_t new_header_size,
                                 uint column_count,
                                 uint new_column_count,
                                 uint add_column_count,
                                 uchar *header_end,
                                 size_t max_offset)
{
  uchar *write;
  uchar *header_base= (uchar *)str->str + FIXED_HEADER_SIZE;
  uint i, j, k;
  size_t curr_offset;

  write= (uchar *)str->str + FIXED_HEADER_SIZE;
  set_fixed_header(str, new_offset_size, new_column_count);

  /*
    Move data first.
    i= index in array of changes
    j= index in packed string header index
  */
  for (curr_offset= 0, i= 0, j= 0;
       i < add_column_count || j < column_count;
       i++)
  {
    size_t UNINIT_VAR(first_offset);
    uint start= j, end;

    /*
      Search in i and j for the next column to add from i and where to
      add.
    */

    while (i < add_column_count && plan[i].act == PLAN_NOP)
      i++;                                    /* skip NOP */

    if (i == add_column_count)
      j= end= column_count;
    else
    {
      /*
        old data portion. We don't need to check that j < column_count
        as plan[i].place is guaranteed to have a pointer inside the
        data.
      */
      while (header_base + j * entry_size < plan[i].place)
        j++;
      end= j;
      if ((plan[i].act == PLAN_REPLACE || plan[i].act == PLAN_DELETE))
        j++;                              /* data at 'j' will be removed */
    }
    plan[i].mv_end= end;

    {
      DYNAMIC_COLUMN_TYPE tp;
      type_and_offset_read_num(&tp, &first_offset,
                               header_base +
                               start * entry_size + COLUMN_NUMBER_SIZE,
                               offset_size);
    }
    /* find data to be moved */
    if (start < end)
    {
      size_t data_size=
        get_length_interval(header_base + start * entry_size,
                            header_base + end * entry_size,
                            header_end, offset_size, max_offset);
      if (data_size == DYNCOL_OFFSET_ERROR ||
          (long) data_size < 0 ||
          data_size > max_offset - first_offset)
      {
        str->length= 0; // just something valid
        return ER_DYNCOL_FORMAT;
      }
      DBUG_ASSERT(curr_offset == first_offset + plan[i].ddelta);
      plan[i].mv_offset= first_offset;
      plan[i].mv_length= data_size;
      curr_offset+= data_size;
    }
    else
    {
      plan[i].mv_length= 0;
      plan[i].mv_offset= curr_offset;
    }

    if (plan[i].ddelta == 0 && offset_size == new_offset_size &&
        plan[i].act != PLAN_DELETE)
      write+= entry_size * (end - start);
    else
    {
      /*
        Adjust all headers since last loop.
        We have to do this as the offset for data has moved
      */
      for (k= start; k < end; k++)
      {
        uchar *read= header_base + k * entry_size;
        size_t offs;
        uint nm;
        DYNAMIC_COLUMN_TYPE tp;

        nm= uint2korr(read);                    /* Column nummber */
        type_and_offset_read_num(&tp, &offs, read + COLUMN_NUMBER_SIZE,
                                 offset_size);
        if (k > start && offs < first_offset)
        {
          str->length= 0; // just something valid
          return ER_DYNCOL_FORMAT;
        }

        offs+= plan[i].ddelta;
        int2store(write, nm);
        /* write rest of data at write + COLUMN_NUMBER_SIZE */
        if (type_and_offset_store_num(write, new_offset_size, tp, offs))
        {
          str->length= 0; // just something valid
          return ER_DYNCOL_FORMAT;
        }
        write+= new_entry_size;
      }
    }

    /* new data adding */
    if (i < add_column_count)
    {
      if( plan[i].act == PLAN_ADD || plan[i].act == PLAN_REPLACE)
      {
        int2store(write, *((uint *)plan[i].key));
        if (type_and_offset_store_num(write, new_offset_size,
                                      plan[i].val[0].type,
                                      curr_offset))
        {
          str->length= 0; // just something valid
          return ER_DYNCOL_FORMAT;
        }
        write+= new_entry_size;
        curr_offset+= plan[i].length;
      }
    }
  }

  /*
    Move headers.
    i= index in array of changes
    j= index in packed string header index
  */
  str->length= (FIXED_HEADER_SIZE + new_header_size);
  for (i= 0, j= 0;
       i < add_column_count || j < column_count;
       i++)
  {
    uint start= j, end;

    /*
      Search in i and j for the next column to add from i and where to
      add.
    */

    while (i < add_column_count && plan[i].act == PLAN_NOP)
      i++;                                    /* skip NOP */

    j= end= plan[i].mv_end;
    if (i != add_column_count &&
        (plan[i].act == PLAN_REPLACE || plan[i].act == PLAN_DELETE))
      j++;

    /* copy first the data that was not replaced in original packed data */
    if (start < end && plan[i].mv_length)
    {
      memmove((header_base + new_header_size +
               plan[i].mv_offset + plan[i].ddelta),
              header_base + header_size + plan[i].mv_offset,
              plan[i].mv_length);
    }
    str->length+= plan[i].mv_length;

    /* new data adding */
    if (i < add_column_count)
    {
      if( plan[i].act == PLAN_ADD || plan[i].act == PLAN_REPLACE)
      {
        data_store(str, plan[i].val, dyncol_fmt_num); /* Append new data */
      }
    }
  }
  return ER_DYNCOL_OK;
}
#endif

/**
  Update the packed string with the given columns

  @param str             String where to write the data
  @param add_column_count Number of columns in the arrays
  @param column_numbers  Array of columns numbers
  @param values          Array of columns values

  @return ER_DYNCOL_* return code
*/
/* plan allocated on the stack */
#define IN_PLACE_PLAN 4

enum enum_dyncol_func_result
dynamic_column_update_many(DYNAMIC_COLUMN *str,
                           uint add_column_count,
                           uint *column_numbers,
                           DYNAMIC_COLUMN_VALUE *values)
{
  return dynamic_column_update_many_fmt(str, add_column_count, column_numbers,
                                        values, FALSE);
}

enum enum_dyncol_func_result
mariadb_dyncol_update_many_num(DYNAMIC_COLUMN *str,
                               uint add_column_count,
                               uint *column_numbers,
                               DYNAMIC_COLUMN_VALUE *values)
{
  return dynamic_column_update_many_fmt(str, add_column_count, column_numbers,
                                        values, FALSE);
}

enum enum_dyncol_func_result
mariadb_dyncol_update_many_named(DYNAMIC_COLUMN *str,
                                 uint add_column_count,
                                 LEX_STRING *column_names,
                                 DYNAMIC_COLUMN_VALUE *values)
{
  return dynamic_column_update_many_fmt(str, add_column_count, column_names,
                                        values, TRUE);
}

static uint numlen(uint val)
{
  uint res;
  if (val == 0)
    return 1;
  res= 0;
  while(val)
  {
    res++;
    val/=10;
  }
  return res;
}

static enum enum_dyncol_func_result
dynamic_column_update_many_fmt(DYNAMIC_COLUMN *str,
                               uint add_column_count,
                               void *column_keys,
                               DYNAMIC_COLUMN_VALUE *values,
                               my_bool string_keys)
{
  PLAN *plan, *alloc_plan= NULL, in_place_plan[IN_PLACE_PLAN];
  uchar *element;
  DYN_HEADER header, new_header;
  struct st_service_funcs *fmt, *new_fmt;
  long long data_delta= 0, name_delta= 0;
  uint i;
  uint not_null;
  long long header_delta= 0;
  long long header_delta_sign, data_delta_sign;
  int copy= FALSE;
  enum enum_dyncol_func_result rc;
  my_bool convert;

  if (add_column_count == 0)
    return ER_DYNCOL_OK;

  bzero(&header, sizeof(header));
  bzero(&new_header, sizeof(new_header));
  new_header.format= (string_keys ? dyncol_fmt_str : dyncol_fmt_num);
  new_fmt= fmt_data + new_header.format;

  /*
    Get columns in column order. As the data in 'str' is already
    in column order this allows to replace all columns in one loop.
  */
  if (IN_PLACE_PLAN > add_column_count)
    plan= in_place_plan;
  else if (!(alloc_plan= plan=
             my_malloc(sizeof(PLAN) * (add_column_count + 1), MYF(0))))
    return ER_DYNCOL_RESOURCE;

  not_null= add_column_count;
  for (i= 0, element= (uchar *) column_keys;
       i < add_column_count;
       i++, element+= new_fmt->key_size_in_array)
  {
    if ((*new_fmt->check_limit)(&element))
    {
      rc= ER_DYNCOL_DATA;
      goto end;
    }

    plan[i].val= values + i;
    plan[i].key= element;
    if (values[i].type == DYN_COL_NULL)
      not_null--;

  }

  if (str->length == 0)
  {
    /*
      Just add new columns. If there was no columns to add we return
      an empty string.
     */
    goto create_new_string;
  }

  /* Check that header is ok */
  if ((rc= init_read_hdr(&header, str)) < 0)
    goto end;
  fmt= fmt_data + header.format;
  /* new format can't be numeric if the old one is names */
  DBUG_ASSERT(new_header.format == dyncol_fmt_str ||
              header.format == dyncol_fmt_num);
  if (header.column_count == 0)
    goto create_new_string;

  qsort(plan, (size_t)add_column_count, sizeof(PLAN), new_fmt->plan_sort);

  new_header.column_count= header.column_count;
  new_header.nmpool_size= header.nmpool_size;
  if ((convert= (new_header.format == dyncol_fmt_str &&
                 header.format == dyncol_fmt_num)))
  {
    DBUG_ASSERT(new_header.nmpool_size == 0);
    for(i= 0, header.entry= header.header;
        i < header.column_count;
        i++, header.entry+= header.entry_size)
    {
      new_header.nmpool_size+= numlen(uint2korr(header.entry));
    }
  }

  if (fmt->fixed_hdr + header.header_size + header.nmpool_size > str->length)
  {
    rc= ER_DYNCOL_FORMAT;
    goto end;
  }

  /*
    Calculate how many columns and data is added/deleted and make a 'plan'
    for each of them.
  */
  for (i= 0; i < add_column_count; i++)
  {
    /*
      For now we don't allow creating two columns with the same number
      at the time of create.  This can be fixed later to just use the later
      by comparing the pointers.
    */
    if (i < add_column_count - 1 &&
        new_fmt->column_sort(&plan[i].key, &plan[i + 1].key) == 0)
    {
      rc= ER_DYNCOL_DATA;
      goto end;
    }

    /* Set common variables for all plans */
    plan[i].ddelta= data_delta;
    plan[i].ndelta= name_delta;
    /* get header delta in entries */
    plan[i].hdelta= header_delta;
    plan[i].length= 0;                          /* Length if NULL */

    if (find_place(&header, plan[i].key, string_keys))
    {
      size_t entry_data_size, entry_name_size= 0;

      /* Data existed; We have to replace or delete it */

      entry_data_size= hdr_interval_length(&header, header.entry +
                                           header.entry_size);
      if (entry_data_size == DYNCOL_OFFSET_ERROR ||
          (long) entry_data_size < 0)
      {
        rc= ER_DYNCOL_FORMAT;
        goto end;
      }

      if (new_header.format == dyncol_fmt_str)
      {
        if (header.format == dyncol_fmt_str)
        {
          LEX_STRING name;
          if (read_name(&header, header.entry, &name))
          {
            rc= ER_DYNCOL_FORMAT;
            goto end;
          }
          entry_name_size= name.length;
        }
        else
          entry_name_size= numlen(uint2korr(header.entry));
      }

      if (plan[i].val->type == DYN_COL_NULL)
      {
        /* Inserting a NULL means delete the old data */

        plan[i].act= PLAN_DELETE;	        /* Remove old value */
        header_delta--;                         /* One row less in header */
        data_delta-= entry_data_size;           /* Less data to store */
        name_delta-= entry_name_size;
      }
      else
      {
        /* Replace the value */

        plan[i].act= PLAN_REPLACE;
        /* get data delta in bytes */
        if ((plan[i].length= dynamic_column_value_len(plan[i].val,
                                                      new_header.format)) ==
            (size_t) ~0)
        {
          rc= ER_DYNCOL_DATA;
          goto end;
        }
        data_delta+= plan[i].length - entry_data_size;
        if (new_header.format == dyncol_fmt_str)
        {
          name_delta+= ((LEX_STRING *)(plan[i].key))->length - entry_name_size;
        }
      }
    }
    else
    {
      /* Data did not exists. Add if it it's not NULL */

      if (plan[i].val->type == DYN_COL_NULL)
      {
        plan[i].act= PLAN_NOP;                  /* Mark entry to be skiped */
      }
      else
      {
        /* Add new value */

        plan[i].act= PLAN_ADD;
        header_delta++;                         /* One more row in header */
        /* get data delta in bytes */
        if ((plan[i].length= dynamic_column_value_len(plan[i].val,
                                                      new_header.format)) ==
            (size_t) ~0)
        {
          rc= ER_DYNCOL_DATA;
          goto end;
        }
        data_delta+= plan[i].length;
        if (new_header.format == dyncol_fmt_str)
          name_delta+= ((LEX_STRING *)plan[i].key)->length;
      }
    }
    plan[i].place= header.entry;
  }
  plan[add_column_count].hdelta= header_delta;
  plan[add_column_count].ddelta= data_delta;
  plan[add_column_count].act= PLAN_NOP;
  plan[add_column_count].place= header.dtpool;

  new_header.column_count= (uint)(header.column_count + header_delta);

  /*
    Check if it is only "increasing" or only "decreasing" plan for (header
    and data separately).
  */
  new_header.data_size= header.data_size + data_delta;
  new_header.nmpool_size= new_header.nmpool_size + name_delta;
  DBUG_ASSERT(new_header.format != dyncol_fmt_num ||
              new_header.nmpool_size == 0);
  if ((new_header.offset_size=
       new_fmt->dynamic_column_offset_bytes(new_header.data_size)) >=
      new_fmt->max_offset_size)
  {
    rc= ER_DYNCOL_LIMIT;
    goto end;
  }

  copy= ((header.format != new_header.format) ||
         (new_header.format == dyncol_fmt_str));
  /* if (new_header.offset_size!=offset_size) then we have to rewrite header */
  header_delta_sign=
    ((int)new_header.offset_size + new_fmt->fixed_hdr_entry) -
    ((int)header.offset_size + fmt->fixed_hdr_entry);
  data_delta_sign= 0;
  // plan[add_column_count] contains last deltas.
  for (i= 0; i <= add_column_count && !copy; i++)
  {
    /* This is the check for increasing/decreasing */
    DELTA_CHECK(header_delta_sign, plan[i].hdelta, copy);
    DELTA_CHECK(data_delta_sign, plan[i].ddelta, copy);
  }
  calc_param(&new_header.entry_size, &new_header.header_size,
             new_fmt->fixed_hdr_entry,
             new_header.offset_size, new_header.column_count);

  /*
    Need copy because:
    1, Header/data parts moved in different directions.
    2. There is no enough allocated space in the string.
    3. Header and data moved in different directions.
  */
  if (copy || /*1.*/
      str->max_length < str->length + header_delta + data_delta || /*2.*/
      ((header_delta_sign < 0 && data_delta_sign > 0) ||
       (header_delta_sign > 0 && data_delta_sign < 0))) /*3.*/
    rc= dynamic_column_update_copy(str, plan, add_column_count,
                                   &header, &new_header,
                                   convert);
  else
    if (header_delta_sign < 0)
      rc= dynamic_column_update_move_left(str, plan, header.offset_size,
                                          header.entry_size,
                                          header.header_size,
                                          new_header.offset_size,
                                          new_header.entry_size,
                                          new_header.header_size,
                                          header.column_count,
                                          new_header.column_count,
                                          add_column_count, header.dtpool,
                                          header.data_size);
    else
      /*
      rc= dynamic_column_update_move_right(str, plan, offset_size,
                                           entry_size,  header_size,
                                           new_header.offset_size,
                                           new_header.entry_size,
                                           new_heder.header_size, column_count,
                                           new_header.column_count,
                                           add_column_count, header_end,
                                           header.data_size);
                                         */
      rc= dynamic_column_update_copy(str, plan, add_column_count,
                                     &header, &new_header,
                                     convert);
end:
  my_free(alloc_plan);
  return rc;

create_new_string:
  /* There is no columns from before, so let's just add the new ones */
  rc= ER_DYNCOL_OK;
  my_free(alloc_plan);
  if (not_null != 0)
    rc= dynamic_column_create_many_internal_fmt(str, add_column_count,
                                                (uint*)column_keys, values,
                                                str->str == NULL,
                                                string_keys);
  goto end;
}


/**
  Update the packed string with the given column

  @param str             String where to write the data
  @param column_number   Array of columns number
  @param values          Array of columns values

  @return ER_DYNCOL_* return code
*/


enum enum_dyncol_func_result
dynamic_column_update(DYNAMIC_COLUMN *str, uint column_nr,
                      DYNAMIC_COLUMN_VALUE *value)
{
  return dynamic_column_update_many(str, 1, &column_nr, value);
}


enum enum_dyncol_func_result
mariadb_dyncol_check(DYNAMIC_COLUMN *str)
{
  struct st_service_funcs *fmt;
  enum enum_dyncol_func_result rc= ER_DYNCOL_FORMAT;
  DYN_HEADER header;
  uint i;
  size_t data_offset= 0, name_offset= 0;
  size_t prev_data_offset= 0, prev_name_offset= 0;
  LEX_STRING name= {0,0}, prev_name= {0,0};
  uint num= 0, prev_num= 0;
  void *key, *prev_key;
  enum enum_dynamic_column_type type= DYN_COL_NULL, prev_type= DYN_COL_NULL;

  DBUG_ENTER("dynamic_column_check");

  if (str->length == 0)
  {
    DBUG_PRINT("info", ("empty string is OK"));
    DBUG_RETURN(ER_DYNCOL_OK);
  }

  bzero(&header, sizeof(header));

  /* Check that header is OK */
  if (read_fixed_header(&header, str))
  {
    DBUG_PRINT("info", ("Reading fixed string header failed"));
    goto end;
  }
  fmt= fmt_data + header.format;
  calc_param(&header.entry_size, &header.header_size,
             fmt->fixed_hdr_entry, header.offset_size,
             header.column_count);
  /* headers are out of string length (no space for data and part of headers) */
  if (fmt->fixed_hdr + header.header_size + header.nmpool_size > str->length)
  {
    DBUG_PRINT("info", ("Fixed header: %u  Header size: %u  "
                        "Name pool size: %u  but Strig length: %u",
                        (uint)fmt->fixed_hdr,
                        (uint)header.header_size,
                        (uint)header.nmpool_size,
                        (uint)str->length));
    goto end;
  }
  header.header= (uchar*)str->str + fmt->fixed_hdr;
  header.nmpool= header.header + header.header_size;
  header.dtpool= header.nmpool + header.nmpool_size;
  header.data_size= str->length - fmt->fixed_hdr -
    header.header_size - header.nmpool_size;

  /* read and check headers */
  if (header.format == dyncol_fmt_num)
  {
    key= &num;
    prev_key= &prev_num;
  }
  else
  {
    key= &name;
    prev_key= &prev_name;
  }
  for (i= 0, header.entry= header.header;
       i < header.column_count;
       i++, header.entry+= header.entry_size)
  {

    if (header.format == dyncol_fmt_num)
    {
       num= uint2korr(header.entry);
    }
    else
    {
      DBUG_ASSERT(header.format == dyncol_fmt_str);
      if (read_name(&header, header.entry, &name))
      {
        DBUG_PRINT("info", ("Reading name failed: Field order: %u"
                            "  Name offset: %u"
                            "  Name pool size: %u",
                            (uint) i,
                            uint2korr(header.entry),
                            (uint)header.nmpool_size));
        goto end;
      }
      name_offset= name.str - (char *)header.nmpool;
    }
    if ((*fmt->type_and_offset_read)(&type, &data_offset,
                                     header.entry + fmt->fixed_hdr_entry,
                                     header.offset_size))
      goto end;

    DBUG_ASSERT(type != DYN_COL_NULL);
    if (data_offset > header.data_size)
    {
      DBUG_PRINT("info", ("Field order: %u  Data offset: %u"
                          " > Data pool size: %u",
                          (uint)i,
                          (uint)data_offset,
                          (uint)header.data_size));
      goto end;
    }
    if (prev_type != DYN_COL_NULL)
    {
      /* It is not first entry */
      if (prev_data_offset >= data_offset)
      {
        DBUG_PRINT("info", ("Field order: %u  Previous data offset: %u"
                            " >= Current data offset: %u",
                            (uint)i,
                            (uint)prev_data_offset,
                            (uint)data_offset));
        goto end;
      }
      if (prev_name_offset > name_offset)
      {
        DBUG_PRINT("info", ("Field order: %u  Previous name offset: %u"
                            " > Current name offset: %u",
                            (uint)i,
                            (uint)prev_data_offset,
                            (uint)data_offset));
        goto end;
      }
      if ((*fmt->column_sort)(&prev_key, &key) >= 0)
      {
        DBUG_PRINT("info", ("Field order: %u  Previous key >= Current key",
                            (uint)i));
        goto end;
      }
    }
    prev_num= num;
    prev_name= name;
    prev_data_offset= data_offset;
    prev_name_offset= name_offset;
    prev_type= type;
  }

  /* check data, which we can */
  for (i= 0, header.entry= header.header;
       i < header.column_count;
       i++, header.entry+= header.entry_size)
  {
    DYNAMIC_COLUMN_VALUE store;
    // already checked by previouse pass
    (*fmt->type_and_offset_read)(&header.type, &header.offset,
                                 header.entry + fmt->fixed_hdr_entry,
                                 header.offset_size);
    header.length=
      hdr_interval_length(&header, header.entry + header.entry_size);
    header.data= header.dtpool + header.offset;
    switch ((header.type)) {
    case DYN_COL_INT:
      rc= dynamic_column_sint_read(&store, header.data, header.length);
      break;
    case DYN_COL_UINT:
      rc= dynamic_column_uint_read(&store, header.data, header.length);
      break;
    case DYN_COL_DOUBLE:
      rc= dynamic_column_double_read(&store, header.data, header.length);
      break;
    case DYN_COL_STRING:
      rc= dynamic_column_string_read(&store, header.data, header.length);
      break;
    case DYN_COL_DECIMAL:
      rc= dynamic_column_decimal_read(&store, header.data, header.length);
      break;
    case DYN_COL_DATETIME:
      rc= dynamic_column_date_time_read(&store, header.data,
                                        header.length);
      break;
    case DYN_COL_DATE:
      rc= dynamic_column_date_read(&store, header.data, header.length);
      break;
    case DYN_COL_TIME:
      rc= dynamic_column_time_read(&store, header.data, header.length);
      break;
    case DYN_COL_DYNCOL:
      rc= dynamic_column_dyncol_read(&store, header.data, header.length);
      break;
    case DYN_COL_NULL:
    default:
      rc= ER_DYNCOL_FORMAT;
      goto end;
    }
    if (rc != ER_DYNCOL_OK)
    {
      DBUG_ASSERT(rc < 0);
      DBUG_PRINT("info", ("Field order: %u  Can't read data: %i",
                          (uint)i, (int) rc));
      goto end;
    }
  }

  rc= ER_DYNCOL_OK;
end:
  DBUG_RETURN(rc);
}


enum enum_dyncol_func_result
mariadb_dyncol_val_str(DYNAMIC_STRING *str, DYNAMIC_COLUMN_VALUE *val,
                       CHARSET_INFO *cs, char quote)
{
  char buff[40];
  size_t len;
  switch (val->type) {
    case DYN_COL_INT:
      len= snprintf(buff, sizeof(buff), "%lld", val->x.long_value);
      if (dynstr_append_mem(str, buff, len))
        return ER_DYNCOL_RESOURCE;
      break;
    case DYN_COL_UINT:
      len= snprintf(buff, sizeof(buff), "%llu", val->x.ulong_value);
      if (dynstr_append_mem(str, buff, len))
        return ER_DYNCOL_RESOURCE;
      break;
    case DYN_COL_DOUBLE:
      len= my_snprintf(buff, sizeof(buff), "%g", val->x.double_value);
      if (dynstr_realloc(str, len + (quote ? 2 : 0)))
        return ER_DYNCOL_RESOURCE;
      if (quote)
        str->str[str->length++]= quote;
      dynstr_append_mem(str, buff, len);
      if (quote)
        str->str[str->length++]= quote;
      break;
    case DYN_COL_DYNCOL:
    case DYN_COL_STRING:
      {
        char *alloc= NULL;
        char *from= val->x.string.value.str;
        ulong bufflen;
        my_bool conv= !my_charset_same(val->x.string.charset, cs);
        my_bool rc;
        len= val->x.string.value.length;
        bufflen= (ulong)(len * (conv ? cs->mbmaxlen : 1));
        if (dynstr_realloc(str, bufflen))
            return ER_DYNCOL_RESOURCE;

        // guaranty UTF-8 string for value
        if (!my_charset_same(val->x.string.charset, cs))
        {
          uint dummy_errors;
          if (!quote)
          {
            /* convert to the destination */
            str->length+= my_convert(str->str, bufflen,
                                     cs,
                                     from, (uint32)len,
                                     val->x.string.charset,
                                     &dummy_errors);
            return ER_DYNCOL_OK;
          }
          if ((alloc= (char *)my_malloc(bufflen, MYF(0))))
          {
            len= my_convert(alloc, bufflen, cs,
                            from, (uint32)len,
                            val->x.string.charset,
                            &dummy_errors);
            from= alloc;
          }
          else
            return ER_DYNCOL_RESOURCE;
        }
        if (quote)
          rc= dynstr_append_quoted(str, from, len, quote);
        else
          rc= dynstr_append_mem(str, from, len);
        if (alloc)
          my_free(alloc);
        if (rc)
          return ER_DYNCOL_RESOURCE;
        break;
      }
    case DYN_COL_DECIMAL:
      {
        int len= sizeof(buff);
        decimal2string(&val->x.decimal.value, buff, &len,
                       0, val->x.decimal.value.frac,
                       '0');
        if (dynstr_append_mem(str, buff, len))
          return ER_DYNCOL_RESOURCE;
        break;
      }
    case DYN_COL_DATETIME:
    case DYN_COL_DATE:
    case DYN_COL_TIME:
      len= my_TIME_to_str(&val->x.time_value, buff, AUTO_SEC_PART_DIGITS);
      if (dynstr_realloc(str, len + (quote ? 2 : 0)))
        return ER_DYNCOL_RESOURCE;
      if (quote)
        str->str[str->length++]= '"';
      dynstr_append_mem(str, buff, len);
      if (quote)
        str->str[str->length++]= '"';
      break;
    case DYN_COL_NULL:
      if (dynstr_append_mem(str, "null", 4))
        return ER_DYNCOL_RESOURCE;
      break;
    default:
      return(ER_DYNCOL_FORMAT);
  }
  return(ER_DYNCOL_OK);
}


enum enum_dyncol_func_result
mariadb_dyncol_val_long(longlong *ll, DYNAMIC_COLUMN_VALUE *val)
{
  enum enum_dyncol_func_result rc= ER_DYNCOL_OK;
  *ll= 0;
  switch (val->type) {
  case DYN_COL_INT:
      *ll= val->x.long_value;
      break;
    case DYN_COL_UINT:
      *ll= (longlong)val->x.ulong_value;
      if (val->x.ulong_value > ULONGLONG_MAX)
         rc= ER_DYNCOL_TRUNCATED;
      break;
    case DYN_COL_DOUBLE:
      *ll= (longlong)val->x.double_value;
      if (((double) *ll) != val->x.double_value)
        rc= ER_DYNCOL_TRUNCATED;
      break;
    case DYN_COL_STRING:
      {
        char *src= val->x.string.value.str;
        size_t len= val->x.string.value.length;
        longlong i= 0, sign= 1;

        while (len && my_isspace(&my_charset_latin1, *src)) src++,len--;

        if (len)
        {
          if (*src == '-')
          {
            sign= -1;
            src++;
          } else if (*src == '-')
            src++;
          while(len && my_isdigit(&my_charset_latin1, *src))
          {
            i= i * 10 + (*src - '0');
            src++;
          }
        }
        else
          rc= ER_DYNCOL_TRUNCATED;
        if (len)
          rc= ER_DYNCOL_TRUNCATED;
        *ll= i * sign;
        break;
      }
    case DYN_COL_DECIMAL:
      if (decimal2longlong(&val->x.decimal.value, ll) != E_DEC_OK)
        rc= ER_DYNCOL_TRUNCATED;
      break;
    case DYN_COL_DATETIME:
      *ll= (val->x.time_value.year * 10000000000ull +
            val->x.time_value.month * 100000000L +
            val->x.time_value.day * 1000000 +
            val->x.time_value.hour * 10000 +
            val->x.time_value.minute * 100 +
            val->x.time_value.second) *
        (val->x.time_value.neg ? -1 : 1);
      break;
    case DYN_COL_DATE:
      *ll= (val->x.time_value.year * 10000 +
            val->x.time_value.month * 100 +
            val->x.time_value.day) *
        (val->x.time_value.neg ? -1 : 1);
      break;
    case DYN_COL_TIME:
      *ll= (val->x.time_value.hour * 10000 +
            val->x.time_value.minute * 100 +
            val->x.time_value.second) *
        (val->x.time_value.neg ? -1 : 1);
      break;
    case DYN_COL_DYNCOL:
    case DYN_COL_NULL:
      rc= ER_DYNCOL_TRUNCATED;
      break;
    default:
      return(ER_DYNCOL_FORMAT);
  }
  return(rc);
}


enum enum_dyncol_func_result
mariadb_dyncol_val_double(double *dbl, DYNAMIC_COLUMN_VALUE *val)
{
  enum enum_dyncol_func_result rc= ER_DYNCOL_OK;
  *dbl= 0;
  switch (val->type) {
  case DYN_COL_INT:
      *dbl= (double)val->x.long_value;
      if (((longlong) *dbl) != val->x.long_value)
        rc= ER_DYNCOL_TRUNCATED;
      break;
    case DYN_COL_UINT:
      *dbl= (double)val->x.ulong_value;
      if (((ulonglong) *dbl) != val->x.ulong_value)
        rc= ER_DYNCOL_TRUNCATED;
      break;
    case DYN_COL_DOUBLE:
      *dbl= val->x.double_value;
      break;
    case DYN_COL_STRING:
      {
        char *str, *end;
        if ((str= malloc(val->x.string.value.length + 1)))
          return ER_DYNCOL_RESOURCE;
        memcpy(str, val->x.string.value.str, val->x.string.value.length);
        str[val->x.string.value.length]= '\0';
        *dbl= strtod(str, &end);
        if (*end != '\0')
          rc= ER_DYNCOL_TRUNCATED;
      }
    case DYN_COL_DECIMAL:
      if (decimal2double(&val->x.decimal.value, dbl) != E_DEC_OK)
        rc= ER_DYNCOL_TRUNCATED;
      break;
    case DYN_COL_DATETIME:
      *dbl= (double)(val->x.time_value.year * 10000000000ull +
                     val->x.time_value.month * 100000000L +
                     val->x.time_value.day * 1000000 +
                     val->x.time_value.hour * 10000 +
                     val->x.time_value.minute * 100 +
                     val->x.time_value.second) *
        (val->x.time_value.neg ? -1 : 1);
      break;
    case DYN_COL_DATE:
      *dbl= (double)(val->x.time_value.year * 10000 +
                     val->x.time_value.month * 100 +
                     val->x.time_value.day) *
        (val->x.time_value.neg ? -1 : 1);
      break;
    case DYN_COL_TIME:
      *dbl= (double)(val->x.time_value.hour * 10000 +
                     val->x.time_value.minute * 100 +
                     val->x.time_value.second) *
        (val->x.time_value.neg ? -1 : 1);
      break;
    case DYN_COL_DYNCOL:
    case DYN_COL_NULL:
      rc= ER_DYNCOL_TRUNCATED;
      break;
    default:
      return(ER_DYNCOL_FORMAT);
  }
  return(rc);
}


/**
  Convert to JSON

  @param str             The packed string
  @param json            Where to put json result

  @return ER_DYNCOL_* return code
*/

#define JSON_STACK_PROTECTION 10

static enum enum_dyncol_func_result
mariadb_dyncol_json_internal(DYNAMIC_COLUMN *str, DYNAMIC_STRING *json,
                             uint lvl)
{
  DYN_HEADER header;
  uint i;
  enum enum_dyncol_func_result rc;

  if (lvl >= JSON_STACK_PROTECTION)
  {
    rc= ER_DYNCOL_RESOURCE;
    goto err;
  }


  if (str->length == 0)
    return ER_DYNCOL_OK;                        /* no columns */

  if ((rc= init_read_hdr(&header, str)) < 0)
    goto err;

  if (header.entry_size * header.column_count + FIXED_HEADER_SIZE >
      str->length)
  {
    rc= ER_DYNCOL_FORMAT;
    goto err;
  }

  rc= ER_DYNCOL_RESOURCE;

  if (dynstr_append_mem(json, "{", 1))
    goto err;
  for (i= 0, header.entry= header.header;
       i < header.column_count;
       i++, header.entry+= header.entry_size)
  {
    DYNAMIC_COLUMN_VALUE val;
    if (i != 0 && dynstr_append_mem(json, ",", 1))
      goto err;
    header.length=
      hdr_interval_length(&header, header.entry + header.entry_size);
    header.data= header.dtpool + header.offset;
    /*
      Check that the found data is withing the ranges. This can happen if
      we get data with wrong offsets.
    */
    if (header.length == DYNCOL_OFFSET_ERROR ||
        header.length > INT_MAX || header.offset > header.data_size)
    {
      rc= ER_DYNCOL_FORMAT;
      goto err;
    }
    if ((rc= dynamic_column_get_value(&header, &val)) < 0)
      goto err;
    if (header.format == dyncol_fmt_num)
    {
      uint nm= uint2korr(header.entry);
      if (dynstr_realloc(json, DYNCOL_NUM_CHAR + 3))
        goto err;
      json->str[json->length++]= '"';
      json->length+= (snprintf(json->str + json->length,
                               DYNCOL_NUM_CHAR, "%u", nm));
    }
    else
    {
      LEX_STRING name;
      if (read_name(&header, header.entry, &name))
      {
        rc= ER_DYNCOL_FORMAT;
        goto err;
      }
      if (dynstr_realloc(json, name.length + 3))
        goto err;
      json->str[json->length++]= '"';
      memcpy(json->str + json->length, name.str, name.length);
      json->length+= name.length;
    }
    json->str[json->length++]= '"';
    json->str[json->length++]= ':';
    if (val.type == DYN_COL_DYNCOL)
    {
      /* here we use it only for read so can cheat a bit */
      DYNAMIC_COLUMN dc;
      bzero(&dc, sizeof(dc));
      dc.str= val.x.string.value.str;
      dc.length= val.x.string.value.length;
      if (mariadb_dyncol_json_internal(&dc, json, lvl + 1) < 0)
      {
        dc.str= NULL; dc.length= 0;
        goto err;
      }
      dc.str= NULL; dc.length= 0;
    }
    else
    {
      if ((rc= mariadb_dyncol_val_str(json, &val,
                                      &my_charset_utf8_general_ci, '"')) < 0)
        goto err;
    }
  }
  if (dynstr_append_mem(json, "}", 1))
  {
    rc= ER_DYNCOL_RESOURCE;
    goto err;
  }
  return ER_DYNCOL_OK;

err:
  json->length= 0;
  return rc;
}

enum enum_dyncol_func_result
mariadb_dyncol_json(DYNAMIC_COLUMN *str, DYNAMIC_STRING *json)
{

  if (init_dynamic_string(json, NULL, str->length * 2, 100))
    return ER_DYNCOL_RESOURCE;

  return mariadb_dyncol_json_internal(str, json, 1);
}


/**
  Convert to DYNAMIC_COLUMN_VALUE values and names (LEX_STING) dynamic array

  @param str             The packed string
  @param count           number of elements in the arrays
  @param names           Where to put names (should be free by user)
  @param vals            Where to put values (should be free by user)

  @return ER_DYNCOL_* return code
*/

enum enum_dyncol_func_result
mariadb_dyncol_unpack(DYNAMIC_COLUMN *str,
                      uint *count,
                      LEX_STRING **names, DYNAMIC_COLUMN_VALUE **vals)
{
  DYN_HEADER header;
  char *nm;
  uint i;
  enum enum_dyncol_func_result rc;

  *count= 0; *names= 0; *vals= 0;

  if (str->length == 0)
    return ER_DYNCOL_OK;                      /* no columns */

  if ((rc= init_read_hdr(&header, str)) < 0)
    return rc;


  if (header.entry_size * header.column_count + FIXED_HEADER_SIZE >
      str->length)
    return ER_DYNCOL_FORMAT;

  *vals= my_malloc(sizeof(DYNAMIC_COLUMN_VALUE)* header.column_count, MYF(0));
  if (header.format == dyncol_fmt_num)
  {
    *names= my_malloc(sizeof(LEX_STRING) * header.column_count +
                      DYNCOL_NUM_CHAR * header.column_count, MYF(0));
    nm= (char *)(names + sizeof(LEX_STRING) * header.column_count);
  }
  else
  {
    *names= my_malloc(sizeof(LEX_STRING) * header.column_count, MYF(0));
    nm= 0;
  }
  if (!(*vals) || !(*names))
  {
    rc= ER_DYNCOL_RESOURCE;
    goto err;
  }

  for (i= 0, header.entry= header.header;
       i < header.column_count;
       i++, header.entry+= header.entry_size)
  {
    header.length=
      hdr_interval_length(&header, header.entry + header.entry_size);
    header.data= header.dtpool + header.offset;
    /*
      Check that the found data is withing the ranges. This can happen if
      we get data with wrong offsets.
    */
    if (header.length == DYNCOL_OFFSET_ERROR ||
        header.length > INT_MAX || header.offset > header.data_size)
    {
      rc= ER_DYNCOL_FORMAT;
      goto err;
    }
    if ((rc= dynamic_column_get_value(&header, (*vals) + i)) < 0)
      goto err;

    if (header.format == dyncol_fmt_num)
    {
      uint num= uint2korr(header.entry);
      (*names)[i].str= nm;
      (*names)[i].length= snprintf(nm, DYNCOL_NUM_CHAR, "%u", num);
      nm+= (*names)[i].length + 1;
    }
    else
    {
      if (read_name(&header, header.entry, (*names) + i))
      {
        rc= ER_DYNCOL_FORMAT;
        goto err;
      }
    }
  }

  *count= header.column_count;
  return ER_DYNCOL_OK;

err:
  if (*vals)
  {
    my_free(*vals);
    *vals= 0;
  }
  if (*names)
  {
    my_free(*names);
    *names= 0;
  }
  return rc;
}

/**
  Get not NULL column count

  @param str             The packed string
  @param column_count    Where to put column count

  @return ER_DYNCOL_* return code
*/

enum enum_dyncol_func_result
mariadb_dyncol_column_count(DYNAMIC_COLUMN *str, uint *column_count)
{
  DYN_HEADER header;
  enum enum_dyncol_func_result rc;

  *(column_count)= 0;
  if (str->length == 0)
    return ER_DYNCOL_OK;

  if ((rc= init_read_hdr(&header, str)) < 0)
    return rc;
  *column_count= header.column_count;
  return rc;
}
/**
 Free dynamic column

 @param str The packed string
*/
void mariadb_dyncol_free(DYNAMIC_COLUMN *str)
{
  dynstr_free(str);
}