summaryrefslogtreecommitdiff
path: root/storage/rocksdb/rdb_datadic.cc
blob: 54cb5e5d402c92cb066aa7b4743d5ad296f23223 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
/*
   Copyright (c) 2012,2013 Monty Program Ab

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

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

/* For use of 'PRIu64': */
#define __STDC_FORMAT_MACROS

#include <my_config.h>
/* This C++ file's header file */
#include "./rdb_datadic.h"

#include <inttypes.h>
/* C++ standard header files */
#include <algorithm>
#include <array>
#include <limits>
#include <map>
#include <set>
#include <utility>
#include <vector>

/* MySQL header files */
#include "./key.h"
#include "./m_ctype.h"
#include "./my_bit.h"

/* MyRocks header files */
#include "./ha_rocksdb_proto.h"
#include "./my_stacktrace.h"
#include "./rdb_cf_manager.h"
#include "./rdb_utils.h"

namespace myrocks {

void get_mem_comparable_space(const CHARSET_INFO *cs,
                              const std::vector<uchar> **xfrm, size_t *xfrm_len,
                              size_t *mb_len);

/*
  MariaDB's stand-in for Field::check_field_name_match that facebook/mysql-5.6
  uses.

  They have that function because of their JSON support, where "a.b.c" is a 
  sub-field of "a.b".
*/

static bool check_field_name_match(Field *field, const char *name)
{
  return (0 == my_strcasecmp(system_charset_info,
                             field->field_name.str,
                             name));
}

/*
  Rdb_key_def class implementation
*/

Rdb_key_def::Rdb_key_def(uint indexnr_arg, uint keyno_arg,
                         rocksdb::ColumnFamilyHandle *cf_handle_arg,
                         uint16_t index_dict_version_arg, uchar index_type_arg,
                         uint16_t kv_format_version_arg, bool is_reverse_cf_arg,
                         bool is_per_partition_cf_arg, const char *_name,
                         Rdb_index_stats _stats, uint32 index_flags_bitmap,
                         uint32 ttl_rec_offset, uint64 ttl_duration)
    : m_index_number(indexnr_arg), m_cf_handle(cf_handle_arg),
      m_index_dict_version(index_dict_version_arg),
      m_index_type(index_type_arg), m_kv_format_version(kv_format_version_arg),
      m_is_reverse_cf(is_reverse_cf_arg),
      m_is_per_partition_cf(is_per_partition_cf_arg), m_name(_name),
      m_stats(_stats), m_index_flags_bitmap(index_flags_bitmap),
      m_ttl_rec_offset(ttl_rec_offset), m_ttl_duration(ttl_duration),
      m_ttl_column(""), m_pk_part_no(nullptr), m_pack_info(nullptr),
      m_keyno(keyno_arg), m_key_parts(0), m_ttl_pk_key_part_offset(UINT_MAX),
      m_ttl_field_offset(UINT_MAX), m_prefix_extractor(nullptr),
      m_maxlength(0)  // means 'not intialized'
{
  mysql_mutex_init(0, &m_mutex, MY_MUTEX_INIT_FAST);
  rdb_netbuf_store_index(m_index_number_storage_form, m_index_number);
  DBUG_ASSERT(m_cf_handle != nullptr);
}

Rdb_key_def::Rdb_key_def(const Rdb_key_def &k)
    : m_index_number(k.m_index_number), m_cf_handle(k.m_cf_handle),
      m_is_reverse_cf(k.m_is_reverse_cf),
      m_is_per_partition_cf(k.m_is_per_partition_cf), m_name(k.m_name),
      m_stats(k.m_stats), m_index_flags_bitmap(k.m_index_flags_bitmap),
      m_ttl_rec_offset(k.m_ttl_rec_offset), m_ttl_duration(k.m_ttl_duration),
      m_ttl_column(k.m_ttl_column), m_pk_part_no(k.m_pk_part_no),
      m_pack_info(k.m_pack_info), m_keyno(k.m_keyno),
      m_key_parts(k.m_key_parts),
      m_ttl_pk_key_part_offset(k.m_ttl_pk_key_part_offset),
      m_ttl_field_offset(UINT_MAX), m_prefix_extractor(k.m_prefix_extractor),
      m_maxlength(k.m_maxlength) {
  mysql_mutex_init(0, &m_mutex, MY_MUTEX_INIT_FAST);
  rdb_netbuf_store_index(m_index_number_storage_form, m_index_number);
  if (k.m_pack_info) {
    const size_t size = sizeof(Rdb_field_packing) * k.m_key_parts;
    m_pack_info =
        reinterpret_cast<Rdb_field_packing *>(my_malloc(size, MYF(0)));
    memcpy(m_pack_info, k.m_pack_info, size);
  }

  if (k.m_pk_part_no) {
    const size_t size = sizeof(uint) * m_key_parts;
    m_pk_part_no = reinterpret_cast<uint *>(my_malloc(size, MYF(0)));
    memcpy(m_pk_part_no, k.m_pk_part_no, size);
  }
}

Rdb_key_def::~Rdb_key_def() {
  mysql_mutex_destroy(&m_mutex);

  my_free(m_pk_part_no);
  m_pk_part_no = nullptr;

  my_free(m_pack_info);
  m_pack_info = nullptr;
}

void Rdb_key_def::setup(const TABLE *const tbl,
                        const Rdb_tbl_def *const tbl_def) {
  DBUG_ASSERT(tbl != nullptr);
  DBUG_ASSERT(tbl_def != nullptr);

  /*
    Set max_length based on the table.  This can be called concurrently from
    multiple threads, so there is a mutex to protect this code.
  */
  const bool is_hidden_pk = (m_index_type == INDEX_TYPE_HIDDEN_PRIMARY);
  const bool hidden_pk_exists = table_has_hidden_pk(tbl);
  const bool secondary_key = (m_index_type == INDEX_TYPE_SECONDARY);
  if (!m_maxlength) {
    RDB_MUTEX_LOCK_CHECK(m_mutex);
    if (m_maxlength != 0) {
      RDB_MUTEX_UNLOCK_CHECK(m_mutex);
      return;
    }

    KEY *key_info = nullptr;
    KEY *pk_info = nullptr;
    if (!is_hidden_pk) {
      key_info = &tbl->key_info[m_keyno];
      if (!hidden_pk_exists)
        pk_info = &tbl->key_info[tbl->s->primary_key];
      m_name = std::string(key_info->name);
    } else {
      m_name = HIDDEN_PK_NAME;
    }

    if (secondary_key)
      m_pk_key_parts= hidden_pk_exists ? 1 : pk_info->ext_key_parts;
    else {
      pk_info = nullptr;
      m_pk_key_parts = 0;
    }

    // "unique" secondary keys support:
    m_key_parts= is_hidden_pk ? 1 : key_info->ext_key_parts;

    if (secondary_key) {
      /*
        In most cases, SQL layer puts PK columns as invisible suffix at the
        end of secondary key. There are cases where this doesn't happen:
        - unique secondary indexes.
        - partitioned tables.

        Internally, we always need PK columns as suffix (and InnoDB does,
        too, if you were wondering).

        The loop below will attempt to put all PK columns at the end of key
        definition.  Columns that are already included in the index (either
        by the user or by "extended keys" feature) are not included for the
        second time.
      */
      m_key_parts += m_pk_key_parts;
    }

    if (secondary_key)
      m_pk_part_no = reinterpret_cast<uint *>(
          my_malloc(sizeof(uint) * m_key_parts, MYF(0)));
    else
      m_pk_part_no = nullptr;

    const size_t size = sizeof(Rdb_field_packing) * m_key_parts;
    m_pack_info =
        reinterpret_cast<Rdb_field_packing *>(my_malloc(size, MYF(0)));

    /*
      Guaranteed not to error here as checks have been made already during
      table creation.
    */
    Rdb_key_def::extract_ttl_col(tbl, tbl_def, &m_ttl_column,
                                 &m_ttl_field_offset, true);

    size_t max_len = INDEX_NUMBER_SIZE;
    int unpack_len = 0;
    int max_part_len = 0;
    bool simulating_extkey = false;
    uint dst_i = 0;

    uint keyno_to_set = m_keyno;
    uint keypart_to_set = 0;

    if (is_hidden_pk) {
      Field *field = nullptr;
      m_pack_info[dst_i].setup(this, field, keyno_to_set, 0, 0);
      m_pack_info[dst_i].m_unpack_data_offset = unpack_len;
      max_len += m_pack_info[dst_i].m_max_image_len;
      max_part_len = std::max(max_part_len, m_pack_info[dst_i].m_max_image_len);
      dst_i++;
    } else {
      KEY_PART_INFO *key_part = key_info->key_part;

      /* this loop also loops over the 'extended key' tail */
      for (uint src_i = 0; src_i < m_key_parts; src_i++, keypart_to_set++) {
        Field *const field = key_part ? key_part->field : nullptr;

        if (simulating_extkey && !hidden_pk_exists) {
          DBUG_ASSERT(secondary_key);
          /* Check if this field is already present in the key definition */
          bool found = false;
          for (uint j= 0; j < key_info->ext_key_parts; j++) {
            if (field->field_index ==
                    key_info->key_part[j].field->field_index &&
                key_part->length == key_info->key_part[j].length) {
              found = true;
              break;
            }
          }

          if (found) {
            key_part++;
            continue;
          }
        }

        if (field && field->real_maybe_null())
          max_len += 1; // NULL-byte

        m_pack_info[dst_i].setup(this, field, keyno_to_set, keypart_to_set,
                                 key_part ? key_part->length : 0);
        m_pack_info[dst_i].m_unpack_data_offset = unpack_len;

        if (pk_info) {
          m_pk_part_no[dst_i] = -1;
          for (uint j = 0; j < m_pk_key_parts; j++) {
            if (field->field_index == pk_info->key_part[j].field->field_index) {
              m_pk_part_no[dst_i] = j;
              break;
            }
          }
        } else if (secondary_key && hidden_pk_exists) {
          /*
            The hidden pk can never be part of the sk.  So it is always
            appended to the end of the sk.
          */
          m_pk_part_no[dst_i] = -1;
          if (simulating_extkey)
            m_pk_part_no[dst_i] = 0;
        }

        max_len += m_pack_info[dst_i].m_max_image_len;

        max_part_len =
            std::max(max_part_len, m_pack_info[dst_i].m_max_image_len);

        /*
          Check key part name here, if it matches the TTL column then we store
          the offset of the TTL key part here.
        */
        if (!m_ttl_column.empty() &&
            check_field_name_match(field, m_ttl_column.c_str())) {
          DBUG_ASSERT(field->real_type() == MYSQL_TYPE_LONGLONG);
          DBUG_ASSERT(field->key_type() == HA_KEYTYPE_ULONGLONG);
          DBUG_ASSERT(!field->real_maybe_null());
          m_ttl_pk_key_part_offset = dst_i;
        }

        key_part++;
        /*
          For "unique" secondary indexes, pretend they have
          "index extensions".

          MariaDB also has this property: if an index has a partially-covered
          column like KEY(varchar_col(N)), then the SQL layer will think it is
          not "extended" with PK columns. The code below handles this case,
          also.
         */
        if (secondary_key && src_i+1 == key_info->ext_key_parts) {
          simulating_extkey = true;
          if (!hidden_pk_exists) {
            keyno_to_set = tbl->s->primary_key;
            key_part = pk_info->key_part;
            keypart_to_set = (uint)-1;
          } else {
            keyno_to_set = tbl_def->m_key_count - 1;
            key_part = nullptr;
            keypart_to_set = 0;
          }
        }

        dst_i++;
      }
    }

    m_key_parts = dst_i;

    /* Initialize the memory needed by the stats structure */
    m_stats.m_distinct_keys_per_prefix.resize(get_key_parts());

    /* Cache prefix extractor for bloom filter usage later */
    rocksdb::Options opt = rdb_get_rocksdb_db()->GetOptions(get_cf());
    m_prefix_extractor = opt.prefix_extractor;

    /*
      This should be the last member variable set before releasing the mutex
      so that other threads can't see the object partially set up.
     */
    m_maxlength = max_len;

    RDB_MUTEX_UNLOCK_CHECK(m_mutex);
  }
}

/*
  Determine if the table has TTL enabled by parsing the table comment.

  @param[IN]  table_arg
  @param[IN]  tbl_def_arg
  @param[OUT] ttl_duration        Default TTL value parsed from table comment
*/
uint Rdb_key_def::extract_ttl_duration(const TABLE *const table_arg,
                                       const Rdb_tbl_def *const tbl_def_arg,
                                       uint64 *ttl_duration) {
  DBUG_ASSERT(table_arg != nullptr);
  DBUG_ASSERT(tbl_def_arg != nullptr);
  DBUG_ASSERT(ttl_duration != nullptr);
  std::string table_comment(table_arg->s->comment.str,
                            table_arg->s->comment.length);

  bool ttl_duration_per_part_match_found = false;
  std::string ttl_duration_str = Rdb_key_def::parse_comment_for_qualifier(
      table_comment, table_arg, tbl_def_arg, &ttl_duration_per_part_match_found,
      RDB_TTL_DURATION_QUALIFIER);

  /* If we don't have a ttl duration, nothing to do here. */
  if (ttl_duration_str.empty()) {
    return HA_EXIT_SUCCESS;
  }

  /*
    Catch errors where a non-integral value was used as ttl duration, strtoull
    will return 0.
  */
  *ttl_duration = std::strtoull(ttl_duration_str.c_str(), nullptr, 0);
  if (!*ttl_duration) {
    my_error(ER_RDB_TTL_DURATION_FORMAT, MYF(0), ttl_duration_str.c_str());
    return HA_EXIT_FAILURE;
  }

  return HA_EXIT_SUCCESS;
}

/*
  Determine if the table has TTL enabled by parsing the table comment.

  @param[IN]  table_arg
  @param[IN]  tbl_def_arg
  @param[OUT] ttl_column          TTL column in the table
  @param[IN]  skip_checks         Skip validation checks (when called in
                                  setup())
*/
uint Rdb_key_def::extract_ttl_col(const TABLE *const table_arg,
                                  const Rdb_tbl_def *const tbl_def_arg,
                                  std::string *ttl_column,
                                  uint *ttl_field_offset, bool skip_checks) {
  std::string table_comment(table_arg->s->comment.str,
                            table_arg->s->comment.length);
  /*
    Check if there is a TTL column specified. Note that this is not required
    and if omitted, an 8-byte ttl field will be prepended to each record
    implicitly.
  */
  bool ttl_col_per_part_match_found = false;
  std::string ttl_col_str = Rdb_key_def::parse_comment_for_qualifier(
      table_comment, table_arg, tbl_def_arg, &ttl_col_per_part_match_found,
      RDB_TTL_COL_QUALIFIER);

  if (skip_checks) {
    for (uint i = 0; i < table_arg->s->fields; i++) {
      Field *const field = table_arg->field[i];
      if (check_field_name_match(field, ttl_col_str.c_str())) {
        *ttl_column = ttl_col_str;
        *ttl_field_offset = i;
      }
    }
    return HA_EXIT_SUCCESS;
  }

  /* Check if TTL column exists in table */
  if (!ttl_col_str.empty()) {
    bool found = false;
    for (uint i = 0; i < table_arg->s->fields; i++) {
      Field *const field = table_arg->field[i];
      if (check_field_name_match(field, ttl_col_str.c_str()) &&
          field->real_type() == MYSQL_TYPE_LONGLONG &&
          field->key_type() == HA_KEYTYPE_ULONGLONG &&
          !field->real_maybe_null()) {
        *ttl_column = ttl_col_str;
        *ttl_field_offset = i;
        found = true;
        break;
      }
    }

    if (!found) {
      my_error(ER_RDB_TTL_COL_FORMAT, MYF(0), ttl_col_str.c_str());
      return HA_EXIT_FAILURE;
    }
  }

  return HA_EXIT_SUCCESS;
}

const std::string
Rdb_key_def::gen_qualifier_for_table(const char *const qualifier,
                                     const std::string &partition_name) {
  bool has_partition = !partition_name.empty();
  std::string qualifier_str = "";

  if (!strcmp(qualifier, RDB_CF_NAME_QUALIFIER)) {
    return has_partition ? gen_cf_name_qualifier_for_partition(partition_name)
                         : qualifier_str + RDB_CF_NAME_QUALIFIER +
                               RDB_QUALIFIER_VALUE_SEP;
  } else if (!strcmp(qualifier, RDB_TTL_DURATION_QUALIFIER)) {
    return has_partition
               ? gen_ttl_duration_qualifier_for_partition(partition_name)
               : qualifier_str + RDB_TTL_DURATION_QUALIFIER +
                     RDB_QUALIFIER_VALUE_SEP;
  } else if (!strcmp(qualifier, RDB_TTL_COL_QUALIFIER)) {
    return has_partition ? gen_ttl_col_qualifier_for_partition(partition_name)
                         : qualifier_str + RDB_TTL_COL_QUALIFIER +
                               RDB_QUALIFIER_VALUE_SEP;
  } else {
    DBUG_ASSERT(0);
  }

  return qualifier_str;
}

/*
  Formats the string and returns the column family name assignment part for a
  specific partition.
*/
const std::string
Rdb_key_def::gen_cf_name_qualifier_for_partition(const std::string &prefix) {
  DBUG_ASSERT(!prefix.empty());

  return prefix + RDB_PER_PARTITION_QUALIFIER_NAME_SEP + RDB_CF_NAME_QUALIFIER +
         RDB_QUALIFIER_VALUE_SEP;
}

const std::string Rdb_key_def::gen_ttl_duration_qualifier_for_partition(
    const std::string &prefix) {
  DBUG_ASSERT(!prefix.empty());

  return prefix + RDB_PER_PARTITION_QUALIFIER_NAME_SEP +
         RDB_TTL_DURATION_QUALIFIER + RDB_QUALIFIER_VALUE_SEP;
}

const std::string
Rdb_key_def::gen_ttl_col_qualifier_for_partition(const std::string &prefix) {
  DBUG_ASSERT(!prefix.empty());

  return prefix + RDB_PER_PARTITION_QUALIFIER_NAME_SEP + RDB_TTL_COL_QUALIFIER +
         RDB_QUALIFIER_VALUE_SEP;
}

const std::string Rdb_key_def::parse_comment_for_qualifier(
    const std::string &comment, const TABLE *const table_arg,
    const Rdb_tbl_def *const tbl_def_arg, bool *per_part_match_found,
    const char *const qualifier) {
  DBUG_ASSERT(table_arg != nullptr);
  DBUG_ASSERT(tbl_def_arg != nullptr);
  DBUG_ASSERT(per_part_match_found != nullptr);
  DBUG_ASSERT(qualifier != nullptr);

  std::string empty_result;

  // Flag which marks if partition specific options were found.
  *per_part_match_found = false;

  if (comment.empty()) {
    return empty_result;
  }

  // Let's fetch the comment for a index and check if there's a custom key
  // name specified for a partition we are handling.
  std::vector<std::string> v =
      myrocks::parse_into_tokens(comment, RDB_QUALIFIER_SEP);

  std::string search_str = gen_qualifier_for_table(qualifier);

  // If table has partitions then we need to check if user has requested
  // qualifiers on a per partition basis.
  //
  // NOTE: this means if you specify a qualifier for a specific partition it
  // will take precedence the 'table level' qualifier if one exists.
  std::string search_str_part;
  if (table_arg->part_info != nullptr) {
    std::string partition_name = tbl_def_arg->base_partition();
    DBUG_ASSERT(!partition_name.empty());
    search_str_part = gen_qualifier_for_table(qualifier, partition_name);
  }

  DBUG_ASSERT(!search_str.empty());

  // Basic O(N) search for a matching assignment. At most we expect maybe
  // ten or so elements here.
  if (!search_str_part.empty()) {
    for (const auto &it : v) {
      if (it.substr(0, search_str_part.length()) == search_str_part) {
        // We found a prefix match. Try to parse it as an assignment.
        std::vector<std::string> tokens =
            myrocks::parse_into_tokens(it, RDB_QUALIFIER_VALUE_SEP);

        // We found a custom qualifier, it was in the form we expected it to be.
        // Return that instead of whatever we initially wanted to return. In
        // a case below the `foo` part will be returned to the caller.
        //
        // p3_cfname=foo
        //
        // If no value was specified then we'll return an empty string which
        // later gets translated into using a default CF.
        if (tokens.size() == 2) {
          *per_part_match_found = true;
          return tokens[1];
        } else {
          return empty_result;
        }
      }
    }
  }

  // Do this loop again, this time searching for 'table level' qualifiers if we
  // didn't find any partition level qualifiers above.
  for (const auto &it : v) {
    if (it.substr(0, search_str.length()) == search_str) {
      std::vector<std::string> tokens =
          myrocks::parse_into_tokens(it, RDB_QUALIFIER_VALUE_SEP);
      if (tokens.size() == 2) {
        return tokens[1];
      } else {
        return empty_result;
      }
    }
  }

  // If we didn't find any partitioned/non-partitioned qualifiers, return an
  // empty string.
  return empty_result;
}

/**
  Read a memcmp key part from a slice using the passed in reader.

  Returns -1 if field was null, 1 if error, 0 otherwise.
*/
int Rdb_key_def::read_memcmp_key_part(const TABLE *table_arg,
                                      Rdb_string_reader *reader,
                                      const uint part_num) const {
  /* It is impossible to unpack the column. Skip it. */
  if (m_pack_info[part_num].m_maybe_null) {
    const char *nullp;
    if (!(nullp = reader->read(1)))
      return 1;
    if (*nullp == 0) {
      /* This is a NULL value */
      return -1;
    } else {
      /* If NULL marker is not '0', it can be only '1'  */
      if (*nullp != 1)
        return 1;
    }
  }

  Rdb_field_packing *fpi = &m_pack_info[part_num];
  DBUG_ASSERT(table_arg->s != nullptr);

  bool is_hidden_pk_part = (part_num + 1 == m_key_parts) &&
                           (table_arg->s->primary_key == MAX_INDEXES);
  Field *field = nullptr;
  if (!is_hidden_pk_part)
    field = fpi->get_field_in_table(table_arg);
  if ((this->*fpi->m_skip_func)(fpi, field, reader))
    return 1;

  return 0;
}

/**
  Get a mem-comparable form of Primary Key from mem-comparable form of this key

  @param
    pk_descr        Primary Key descriptor
    key             Index tuple from this key in mem-comparable form
    pk_buffer  OUT  Put here mem-comparable form of the Primary Key.

  @note
    It may or may not be possible to restore primary key columns to their
    mem-comparable form.  To handle all cases, this function copies mem-
    comparable forms directly.

    RocksDB SE supports "Extended keys". This means that PK columns are present
    at the end of every key.  If the key already includes PK columns, then
    these columns are not present at the end of the key.

    Because of the above, we copy each primary key column.

  @todo
    If we checked crc32 checksums in this function, we would catch some CRC
    violations that we currently don't. On the other hand, there is a broader
    set of queries for which we would check the checksum twice.
*/

uint Rdb_key_def::get_primary_key_tuple(const TABLE *const table,
                                        const Rdb_key_def &pk_descr,
                                        const rocksdb::Slice *const key,
                                        uchar *const pk_buffer) const {
  DBUG_ASSERT(table != nullptr);
  DBUG_ASSERT(key != nullptr);
  DBUG_ASSERT(pk_buffer);

  uint size = 0;
  uchar *buf = pk_buffer;
  DBUG_ASSERT(m_pk_key_parts);

  /* Put the PK number */
  rdb_netbuf_store_index(buf, pk_descr.m_index_number);
  buf += INDEX_NUMBER_SIZE;
  size += INDEX_NUMBER_SIZE;

  const char *start_offs[MAX_REF_PARTS];
  const char *end_offs[MAX_REF_PARTS];
  int pk_key_part;
  uint i;
  Rdb_string_reader reader(key);

  // Skip the index number
  if ((!reader.read(INDEX_NUMBER_SIZE)))
    return RDB_INVALID_KEY_LEN;

  for (i = 0; i < m_key_parts; i++) {
    if ((pk_key_part = m_pk_part_no[i]) != -1) {
      start_offs[pk_key_part] = reader.get_current_ptr();
    }

    if (read_memcmp_key_part(table, &reader, i) > 0) {
      return RDB_INVALID_KEY_LEN;
    }

    if (pk_key_part != -1) {
      end_offs[pk_key_part] = reader.get_current_ptr();
    }
  }

  for (i = 0; i < m_pk_key_parts; i++) {
    const uint part_size = end_offs[i] - start_offs[i];
    memcpy(buf, start_offs[i], end_offs[i] - start_offs[i]);
    buf += part_size;
    size += part_size;
  }

  return size;
}

/**
  Get a mem-comparable form of Secondary Key from mem-comparable form of this
  key, without the extended primary key tail.

  @param
    key                Index tuple from this key in mem-comparable form
    sk_buffer     OUT  Put here mem-comparable form of the Secondary Key.
    n_null_fields OUT  Put number of null fields contained within sk entry
*/
uint Rdb_key_def::get_memcmp_sk_parts(const TABLE *table,
                                      const rocksdb::Slice &key,
                                      uchar *sk_buffer,
                                      uint *n_null_fields) const {
  DBUG_ASSERT(table != nullptr);
  DBUG_ASSERT(sk_buffer != nullptr);
  DBUG_ASSERT(n_null_fields != nullptr);
  DBUG_ASSERT(m_keyno != table->s->primary_key && !table_has_hidden_pk(table));

  uchar *buf = sk_buffer;

  int res;
  Rdb_string_reader reader(&key);
  const char *start = reader.get_current_ptr();

  // Skip the index number
  if ((!reader.read(INDEX_NUMBER_SIZE)))
    return RDB_INVALID_KEY_LEN;

  for (uint i = 0; i < table->key_info[m_keyno].user_defined_key_parts; i++) {
    if ((res = read_memcmp_key_part(table, &reader, i)) > 0) {
      return RDB_INVALID_KEY_LEN;
    } else if (res == -1) {
      (*n_null_fields)++;
    }
  }

  uint sk_memcmp_len = reader.get_current_ptr() - start;
  memcpy(buf, start, sk_memcmp_len);
  return sk_memcmp_len;
}

/**
  Convert index tuple into storage (i.e. mem-comparable) format

  @detail
    Currently this is done by unpacking into table->record[0] and then
    packing index columns into storage format.

  @param pack_buffer Temporary area for packing varchar columns. Its
                     size is at least max_storage_fmt_length() bytes.
*/

uint Rdb_key_def::pack_index_tuple(TABLE *const tbl, uchar *const pack_buffer,
                                   uchar *const packed_tuple,
                                   const uchar *const key_tuple,
                                   const key_part_map &keypart_map) const {
  DBUG_ASSERT(tbl != nullptr);
  DBUG_ASSERT(pack_buffer != nullptr);
  DBUG_ASSERT(packed_tuple != nullptr);
  DBUG_ASSERT(key_tuple != nullptr);

  /* We were given a record in KeyTupleFormat. First, save it to record */
  const uint key_len = calculate_key_len(tbl, m_keyno, key_tuple, keypart_map);
  key_restore(tbl->record[0], key_tuple, &tbl->key_info[m_keyno], key_len);

  uint n_used_parts = my_count_bits(keypart_map);
  if (keypart_map == HA_WHOLE_KEY)
    n_used_parts = 0; // Full key is used

  /* Then, convert the record into a mem-comparable form */
  return pack_record(tbl, pack_buffer, tbl->record[0], packed_tuple, nullptr,
                     false, 0, n_used_parts);
}

/**
  @brief
    Check if "unpack info" data includes checksum.

  @detail
    This is used only by CHECK TABLE to count the number of rows that have
    checksums.
*/

bool Rdb_key_def::unpack_info_has_checksum(const rocksdb::Slice &unpack_info) {
  const uchar *ptr = (const uchar *)unpack_info.data();
  size_t size = unpack_info.size();

  // Skip unpack info if present.
  if (size >= RDB_UNPACK_HEADER_SIZE && ptr[0] == RDB_UNPACK_DATA_TAG) {
    const uint16 skip_len = rdb_netbuf_to_uint16(ptr + 1);
    SHIP_ASSERT(size >= skip_len);

    size -= skip_len;
    ptr += skip_len;
  }

  return (size == RDB_CHECKSUM_CHUNK_SIZE && ptr[0] == RDB_CHECKSUM_DATA_TAG);
}

/*
  @return Number of bytes that were changed
*/
int Rdb_key_def::successor(uchar *const packed_tuple, const uint &len) {
  DBUG_ASSERT(packed_tuple != nullptr);

  int changed = 0;
  uchar *p = packed_tuple + len - 1;
  for (; p > packed_tuple; p--) {
    changed++;
    if (*p != uchar(0xFF)) {
      *p = *p + 1;
      break;
    }
    *p = '\0';
  }
  return changed;
}

uchar *Rdb_key_def::pack_field(Field *const field, Rdb_field_packing *pack_info,
                               uchar *tuple, uchar *const packed_tuple,
                               uchar *const pack_buffer,
                               Rdb_string_writer *const unpack_info,
                               uint *const n_null_fields) const {
  if (field->real_maybe_null()) {
    DBUG_ASSERT(is_storage_available(tuple - packed_tuple, 1));
    if (field->is_real_null()) {
      /* NULL value. store '\0' so that it sorts before non-NULL values */
      *tuple++ = 0;
      /* That's it, don't store anything else */
      if (n_null_fields)
        (*n_null_fields)++;
      return tuple;
    } else {
      /* Not a NULL value. Store '1' */
      *tuple++ = 1;
    }
  }

  const bool create_unpack_info =
      (unpack_info &&  // we were requested to generate unpack_info
       pack_info->uses_unpack_info());  // and this keypart uses it
  Rdb_pack_field_context pack_ctx(unpack_info);

  // Set the offset for methods which do not take an offset as an argument
  DBUG_ASSERT(is_storage_available(tuple - packed_tuple,
                                   pack_info->m_max_image_len));

  (this->*pack_info->m_pack_func)(pack_info, field, pack_buffer, &tuple,
                                  &pack_ctx);

  /* Make "unpack info" to be stored in the value */
  if (create_unpack_info) {
    (this->*pack_info->m_make_unpack_info_func)(pack_info->m_charset_codec,
                                                field, &pack_ctx);
  }

  return tuple;
}

/**
  Get index columns from the record and pack them into mem-comparable form.

  @param
    tbl                   Table we're working on
    record           IN   Record buffer with fields in table->record format
    pack_buffer      IN   Temporary area for packing varchars. The size is
                          at least max_storage_fmt_length() bytes.
    packed_tuple     OUT  Key in the mem-comparable form
    unpack_info      OUT  Unpack data
    unpack_info_len  OUT  Unpack data length
    n_key_parts           Number of keyparts to process. 0 means all of them.
    n_null_fields    OUT  Number of key fields with NULL value.
    ttl_pk_offset    OUT  Offset of the ttl column if specified and in the key

  @detail
    Some callers do not need the unpack information, they can pass
    unpack_info=nullptr, unpack_info_len=nullptr.

  @return
    Length of the packed tuple
*/

uint Rdb_key_def::pack_record(const TABLE *const tbl, uchar *const pack_buffer,
                              const uchar *const record,
                              uchar *const packed_tuple,
                              Rdb_string_writer *const unpack_info,
                              const bool &should_store_row_debug_checksums,
                              const longlong &hidden_pk_id, uint n_key_parts,
                              uint *const n_null_fields,
                              uint *const ttl_pk_offset) const {
  DBUG_ASSERT(tbl != nullptr);
  DBUG_ASSERT(pack_buffer != nullptr);
  DBUG_ASSERT(record != nullptr);
  DBUG_ASSERT(packed_tuple != nullptr);
  // Checksums for PKs are made when record is packed.
  // We should never attempt to make checksum just from PK values
  DBUG_ASSERT_IMP(should_store_row_debug_checksums,
                  (m_index_type == INDEX_TYPE_SECONDARY));

  uchar *tuple = packed_tuple;
  size_t unpack_len_pos = size_t(-1);
  const bool hidden_pk_exists = table_has_hidden_pk(tbl);

  rdb_netbuf_store_index(tuple, m_index_number);
  tuple += INDEX_NUMBER_SIZE;

  // If n_key_parts is 0, it means all columns.
  // The following includes the 'extended key' tail.
  // The 'extended key' includes primary key. This is done to 'uniqify'
  // non-unique indexes
  const bool use_all_columns = n_key_parts == 0 || n_key_parts == MAX_REF_PARTS;

  // If hidden pk exists, but hidden pk wasnt passed in, we can't pack the
  // hidden key part.  So we skip it (its always 1 part).
  if (hidden_pk_exists && !hidden_pk_id && use_all_columns)
    n_key_parts = m_key_parts - 1;
  else if (use_all_columns)
    n_key_parts = m_key_parts;

  if (n_null_fields)
    *n_null_fields = 0;

  if (unpack_info) {
    unpack_info->clear();
    unpack_info->write_uint8(RDB_UNPACK_DATA_TAG);
    unpack_len_pos = unpack_info->get_current_pos();
    // we don't know the total length yet, so write a zero
    unpack_info->write_uint16(0);
  }

  for (uint i = 0; i < n_key_parts; i++) {
    // Fill hidden pk id into the last key part for secondary keys for tables
    // with no pk
    if (hidden_pk_exists && hidden_pk_id && i + 1 == n_key_parts) {
      m_pack_info[i].fill_hidden_pk_val(&tuple, hidden_pk_id);
      break;
    }

    Field *const field = m_pack_info[i].get_field_in_table(tbl);
    DBUG_ASSERT(field != nullptr);

    uint field_offset = field->ptr - tbl->record[0];
    uint null_offset = field->null_offset(tbl->record[0]);
    bool maybe_null = field->real_maybe_null();

    // Save the ttl duration offset in the key so we can store it in front of
    // the record later.
    if (ttl_pk_offset && m_ttl_duration > 0 && i == m_ttl_pk_key_part_offset) {
      DBUG_ASSERT(check_field_name_match(field, m_ttl_column.c_str()));
      DBUG_ASSERT(field->real_type() == MYSQL_TYPE_LONGLONG);
      DBUG_ASSERT(field->key_type() == HA_KEYTYPE_ULONGLONG);
      DBUG_ASSERT(!field->real_maybe_null());
      *ttl_pk_offset = tuple - packed_tuple;
    }

    field->move_field(const_cast<uchar*>(record) + field_offset,
        maybe_null ? const_cast<uchar*>(record) + null_offset : nullptr,
        field->null_bit);
    // WARNING! Don't return without restoring field->ptr and field->null_ptr

    tuple = pack_field(field, &m_pack_info[i], tuple, packed_tuple, pack_buffer,
                       unpack_info, n_null_fields);

    // Restore field->ptr and field->null_ptr
    field->move_field(tbl->record[0] + field_offset,
                      maybe_null ? tbl->record[0] + null_offset : nullptr,
                      field->null_bit);
  }

  if (unpack_info) {
    const size_t len = unpack_info->get_current_pos();
    DBUG_ASSERT(len <= std::numeric_limits<uint16_t>::max());

    // Don't store the unpack_info if it has only the header (that is, there's
    // no meaningful content).
    // Primary Keys are special: for them, store the unpack_info even if it's
    // empty (provided m_maybe_unpack_info==true, see
    // ha_rocksdb::convert_record_to_storage_format)
    if (len == RDB_UNPACK_HEADER_SIZE &&
        m_index_type != Rdb_key_def::INDEX_TYPE_PRIMARY) {
      unpack_info->clear();
    } else {
      unpack_info->write_uint16_at(unpack_len_pos, len);
    }

    //
    // Secondary keys have key and value checksums in the value part
    // Primary key is a special case (the value part has non-indexed columns),
    // so the checksums are computed and stored by
    // ha_rocksdb::convert_record_to_storage_format
    //
    if (should_store_row_debug_checksums) {
      const uint32_t key_crc32 = crc32(0, packed_tuple, tuple - packed_tuple);
      const uint32_t val_crc32 =
          crc32(0, unpack_info->ptr(), unpack_info->get_current_pos());

      unpack_info->write_uint8(RDB_CHECKSUM_DATA_TAG);
      unpack_info->write_uint32(key_crc32);
      unpack_info->write_uint32(val_crc32);
    }
  }

  DBUG_ASSERT(is_storage_available(tuple - packed_tuple, 0));

  return tuple - packed_tuple;
}

/**
  Pack the hidden primary key into mem-comparable form.

  @param
    tbl                   Table we're working on
    hidden_pk_id     IN   New value to be packed into key
    packed_tuple     OUT  Key in the mem-comparable form

  @return
    Length of the packed tuple
*/

uint Rdb_key_def::pack_hidden_pk(const longlong &hidden_pk_id,
                                 uchar *const packed_tuple) const {
  DBUG_ASSERT(packed_tuple != nullptr);

  uchar *tuple = packed_tuple;
  rdb_netbuf_store_index(tuple, m_index_number);
  tuple += INDEX_NUMBER_SIZE;
  DBUG_ASSERT(m_key_parts == 1);
  DBUG_ASSERT(is_storage_available(tuple - packed_tuple,
                                   m_pack_info[0].m_max_image_len));

  m_pack_info[0].fill_hidden_pk_val(&tuple, hidden_pk_id);

  DBUG_ASSERT(is_storage_available(tuple - packed_tuple, 0));
  return tuple - packed_tuple;
}

/*
  Function of type rdb_index_field_pack_t
*/

void Rdb_key_def::pack_with_make_sort_key(
    Rdb_field_packing *const fpi, Field *const field,
    uchar *const buf MY_ATTRIBUTE((__unused__)), uchar **dst,
    Rdb_pack_field_context *const pack_ctx MY_ATTRIBUTE((__unused__))) const {
  DBUG_ASSERT(fpi != nullptr);
  DBUG_ASSERT(field != nullptr);
  DBUG_ASSERT(dst != nullptr);
  DBUG_ASSERT(*dst != nullptr);

  const int max_len = fpi->m_max_image_len;
  my_bitmap_map *old_map;

  old_map= dbug_tmp_use_all_columns(field->table,
                                    field->table->read_set);
  field->sort_string(*dst, max_len);
  dbug_tmp_restore_column_map(field->table->read_set, old_map);
  *dst += max_len;
}

/*
  Compares two keys without unpacking

  @detail
  @return
    0 - Ok. column_index is the index of the first column which is different.
          -1 if two kes are equal
    1 - Data format error.
*/
int Rdb_key_def::compare_keys(const rocksdb::Slice *key1,
                              const rocksdb::Slice *key2,
                              std::size_t *const column_index) const {
  DBUG_ASSERT(key1 != nullptr);
  DBUG_ASSERT(key2 != nullptr);
  DBUG_ASSERT(column_index != nullptr);

  // the caller should check the return value and
  // not rely on column_index being valid
  *column_index = 0xbadf00d;

  Rdb_string_reader reader1(key1);
  Rdb_string_reader reader2(key2);

  // Skip the index number
  if ((!reader1.read(INDEX_NUMBER_SIZE)))
    return HA_EXIT_FAILURE;

  if ((!reader2.read(INDEX_NUMBER_SIZE)))
    return HA_EXIT_FAILURE;

  for (uint i = 0; i < m_key_parts; i++) {
    const Rdb_field_packing *const fpi = &m_pack_info[i];
    if (fpi->m_maybe_null) {
      const auto nullp1 = reader1.read(1);
      const auto nullp2 = reader2.read(1);

      if (nullp1 == nullptr || nullp2 == nullptr) {
        return HA_EXIT_FAILURE;
      }

      if (*nullp1 != *nullp2) {
        *column_index = i;
        return HA_EXIT_SUCCESS;
      }

      if (*nullp1 == 0) {
        /* This is a NULL value */
        continue;
      }
    }

    const auto before_skip1 = reader1.get_current_ptr();
    const auto before_skip2 = reader2.get_current_ptr();
    DBUG_ASSERT(fpi->m_skip_func);
    if ((this->*fpi->m_skip_func)(fpi, nullptr, &reader1))
      return HA_EXIT_FAILURE;
    if ((this->*fpi->m_skip_func)(fpi, nullptr, &reader2))
      return HA_EXIT_FAILURE;
    const auto size1 = reader1.get_current_ptr() - before_skip1;
    const auto size2 = reader2.get_current_ptr() - before_skip2;
    if (size1 != size2) {
      *column_index = i;
      return HA_EXIT_SUCCESS;
    }

    if (memcmp(before_skip1, before_skip2, size1) != 0) {
      *column_index = i;
      return HA_EXIT_SUCCESS;
    }
  }

  *column_index = m_key_parts;
  return HA_EXIT_SUCCESS;
}

/*
  @brief
    Given a zero-padded key, determine its real key length

  @detail
    Fixed-size skip functions just read.
*/

size_t Rdb_key_def::key_length(const TABLE *const table,
                               const rocksdb::Slice &key) const {
  DBUG_ASSERT(table != nullptr);

  Rdb_string_reader reader(&key);

  if ((!reader.read(INDEX_NUMBER_SIZE)))
    return size_t(-1);

  for (uint i = 0; i < m_key_parts; i++) {
    const Rdb_field_packing *fpi = &m_pack_info[i];
    const Field *field = nullptr;
    if (m_index_type != INDEX_TYPE_HIDDEN_PRIMARY)
      field = fpi->get_field_in_table(table);
    if ((this->*fpi->m_skip_func)(fpi, field, &reader))
      return size_t(-1);
  }
  return key.size() - reader.remaining_bytes();
}

int Rdb_key_def::unpack_field(
    Rdb_field_packing *const fpi,
    Field *const             field,
    Rdb_string_reader*       reader,
    const uchar *const       default_value,
    Rdb_string_reader*       unp_reader) const
{
  if (fpi->m_maybe_null) {
    const char *nullp;
    if (!(nullp = reader->read(1))) {
      return HA_EXIT_FAILURE;
    }

    if (*nullp == 0) {
      /* Set the NULL-bit of this field */
      field->set_null();
      /* Also set the field to its default value */
      memcpy(field->ptr, default_value, field->pack_length());
      return HA_EXIT_SUCCESS;
    } else if (*nullp == 1) {
      field->set_notnull();
    } else {
      return HA_EXIT_FAILURE;
    }
  }

  return (this->*fpi->m_unpack_func)(fpi, field, field->ptr, reader,
                                     unp_reader);
}

/*
  Take mem-comparable form and unpack_info and unpack it to Table->record

  @detail
    not all indexes support this

  @return
    HA_EXIT_SUCCESS    OK
    other              HA_ERR error code
*/

int Rdb_key_def::unpack_record(TABLE *const table, uchar *const buf,
                               const rocksdb::Slice *const packed_key,
                               const rocksdb::Slice *const unpack_info,
                               const bool &verify_row_debug_checksums) const {
  Rdb_string_reader reader(packed_key);
  Rdb_string_reader unp_reader = Rdb_string_reader::read_or_empty(unpack_info);

  const bool is_hidden_pk = (m_index_type == INDEX_TYPE_HIDDEN_PRIMARY);
  const bool hidden_pk_exists = table_has_hidden_pk(table);
  const bool secondary_key = (m_index_type == INDEX_TYPE_SECONDARY);
  // There is no checksuming data after unpack_info for primary keys, because
  // the layout there is different. The checksum is verified in
  // ha_rocksdb::convert_record_from_storage_format instead.
  DBUG_ASSERT_IMP(!secondary_key, !verify_row_debug_checksums);

  // Skip the index number
  if ((!reader.read(INDEX_NUMBER_SIZE))) {
    return HA_ERR_ROCKSDB_CORRUPT_DATA;
  }

  // For secondary keys, we expect the value field to contain unpack data and
  // checksum data in that order. One or both can be missing, but they cannot
  // be reordered.
  const bool has_unpack_info =
      unp_reader.remaining_bytes() &&
      *unp_reader.get_current_ptr() == RDB_UNPACK_DATA_TAG;
  if (has_unpack_info && !unp_reader.read(RDB_UNPACK_HEADER_SIZE)) {
    return HA_ERR_ROCKSDB_CORRUPT_DATA;
  }

  for (uint i = 0; i < m_key_parts; i++) {
    Rdb_field_packing *const fpi = &m_pack_info[i];

    /*
      Hidden pk field is packed at the end of the secondary keys, but the SQL
      layer does not know about it. Skip retrieving field if hidden pk.
    */
    if ((secondary_key && hidden_pk_exists && i + 1 == m_key_parts) ||
        is_hidden_pk) {
      DBUG_ASSERT(fpi->m_unpack_func);
      if ((this->*fpi->m_skip_func)(fpi, nullptr, &reader)) {
        return HA_ERR_ROCKSDB_CORRUPT_DATA;
      }
      continue;
    }

    Field *const field = fpi->get_field_in_table(table);

    if (fpi->m_unpack_func) {
      /* It is possible to unpack this column. Do it. */

      uint field_offset = field->ptr - table->record[0];
      uint null_offset = field->null_offset();
      bool maybe_null = field->real_maybe_null();
      field->move_field(buf + field_offset,
                        maybe_null ? buf + null_offset : nullptr,
                        field->null_bit);
      // WARNING! Don't return without restoring field->ptr and field->null_ptr

      // If we need unpack info, but there is none, tell the unpack function
      // this by passing unp_reader as nullptr. If we never read unpack_info
      // during unpacking anyway, then there won't an error.
      const bool maybe_missing_unpack =
          !has_unpack_info && fpi->uses_unpack_info();
      int res = unpack_field(fpi, field, &reader,
                             table->s->default_values + field_offset,
                             maybe_missing_unpack ? nullptr : &unp_reader);

      // Restore field->ptr and field->null_ptr
      field->move_field(table->record[0] + field_offset,
                        maybe_null ? table->record[0] + null_offset : nullptr,
                        field->null_bit);

      if (res != UNPACK_SUCCESS) {
        return HA_ERR_ROCKSDB_CORRUPT_DATA;
      }
    } else {
      /* It is impossible to unpack the column. Skip it. */
      if (fpi->m_maybe_null) {
        const char *nullp;
        if (!(nullp = reader.read(1)))
          return HA_ERR_ROCKSDB_CORRUPT_DATA;
        if (*nullp == 0) {
          /* This is a NULL value */
          continue;
        }
        /* If NULL marker is not '0', it can be only '1'  */
        if (*nullp != 1)
          return HA_ERR_ROCKSDB_CORRUPT_DATA;
      }
      if ((this->*fpi->m_skip_func)(fpi, field, &reader))
        return HA_ERR_ROCKSDB_CORRUPT_DATA;
    }
  }

  /*
    Check checksum values if present
  */
  const char *ptr;
  if ((ptr = unp_reader.read(1)) && *ptr == RDB_CHECKSUM_DATA_TAG) {
    if (verify_row_debug_checksums) {
      uint32_t stored_key_chksum = rdb_netbuf_to_uint32(
          (const uchar *)unp_reader.read(RDB_CHECKSUM_SIZE));
      const uint32_t stored_val_chksum = rdb_netbuf_to_uint32(
          (const uchar *)unp_reader.read(RDB_CHECKSUM_SIZE));

      const uint32_t computed_key_chksum =
          crc32(0, (const uchar *)packed_key->data(), packed_key->size());
      const uint32_t computed_val_chksum =
          crc32(0, (const uchar *)unpack_info->data(),
                unpack_info->size() - RDB_CHECKSUM_CHUNK_SIZE);

      DBUG_EXECUTE_IF("myrocks_simulate_bad_key_checksum1",
                      stored_key_chksum++;);

      if (stored_key_chksum != computed_key_chksum) {
        report_checksum_mismatch(true, packed_key->data(), packed_key->size());
        return HA_ERR_ROCKSDB_CHECKSUM_MISMATCH;
      }

      if (stored_val_chksum != computed_val_chksum) {
        report_checksum_mismatch(false, unpack_info->data(),
                                 unpack_info->size() - RDB_CHECKSUM_CHUNK_SIZE);
        return HA_ERR_ROCKSDB_CHECKSUM_MISMATCH;
      }
    } else {
      /* The checksums are present but we are not checking checksums */
    }
  }

  if (reader.remaining_bytes())
    return HA_ERR_ROCKSDB_CORRUPT_DATA;

  return HA_EXIT_SUCCESS;
}

bool Rdb_key_def::table_has_hidden_pk(const TABLE *const table) {
  return table->s->primary_key == MAX_INDEXES;
}

void Rdb_key_def::report_checksum_mismatch(const bool &is_key,
                                           const char *const data,
                                           const size_t data_size) const {
  // NO_LINT_DEBUG
  sql_print_error("Checksum mismatch in %s of key-value pair for index 0x%x",
                  is_key ? "key" : "value", get_index_number());

  const std::string buf = rdb_hexdump(data, data_size, RDB_MAX_HEXDUMP_LEN);
  // NO_LINT_DEBUG
  sql_print_error("Data with incorrect checksum (%" PRIu64 " bytes): %s",
                  (uint64_t)data_size, buf.c_str());

  my_error(ER_INTERNAL_ERROR, MYF(0), "Record checksum mismatch");
}

bool Rdb_key_def::index_format_min_check(const int &pk_min,
                                         const int &sk_min) const {
  switch (m_index_type) {
  case INDEX_TYPE_PRIMARY:
  case INDEX_TYPE_HIDDEN_PRIMARY:
    return (m_kv_format_version >= pk_min);
  case INDEX_TYPE_SECONDARY:
    return (m_kv_format_version >= sk_min);
  default:
    DBUG_ASSERT(0);
    return false;
  }
}

///////////////////////////////////////////////////////////////////////////////////////////
// Rdb_field_packing
///////////////////////////////////////////////////////////////////////////////////////////

/*
  Function of type rdb_index_field_skip_t
*/

int Rdb_key_def::skip_max_length(const Rdb_field_packing *const fpi,
                                 const Field *const field
                                     MY_ATTRIBUTE((__unused__)),
                                 Rdb_string_reader *const reader) const {
  if (!reader->read(fpi->m_max_image_len))
    return HA_EXIT_FAILURE;
  return HA_EXIT_SUCCESS;
}

/*
  (RDB_ESCAPE_LENGTH-1) must be an even number so that pieces of lines are not
  split in the middle of an UTF-8 character. See the implementation of
  unpack_binary_or_utf8_varchar.
*/

#define RDB_ESCAPE_LENGTH 9
#define RDB_LEGACY_ESCAPE_LENGTH RDB_ESCAPE_LENGTH
static_assert((RDB_ESCAPE_LENGTH - 1) % 2 == 0,
              "RDB_ESCAPE_LENGTH-1 must be even.");

#define RDB_ENCODED_SIZE(len)                                                  \
  ((len + (RDB_ESCAPE_LENGTH - 2)) / (RDB_ESCAPE_LENGTH - 1)) *                \
      RDB_ESCAPE_LENGTH

#define RDB_LEGACY_ENCODED_SIZE(len)                                           \
  ((len + (RDB_LEGACY_ESCAPE_LENGTH - 1)) / (RDB_LEGACY_ESCAPE_LENGTH - 1)) *  \
      RDB_LEGACY_ESCAPE_LENGTH

/*
  Function of type rdb_index_field_skip_t
*/

int Rdb_key_def::skip_variable_length(
    const Rdb_field_packing *const fpi MY_ATTRIBUTE((__unused__)),
    const Field *const field, Rdb_string_reader *const reader) const {
  const uchar *ptr;
  bool finished = false;

  size_t dst_len; /* How much data can be there */
  if (field) {
    const Field_varstring *const field_var =
        static_cast<const Field_varstring *>(field);
    dst_len = field_var->pack_length() - field_var->length_bytes;
  } else {
    dst_len = UINT_MAX;
  }

  bool use_legacy_format = use_legacy_varbinary_format();

  /* Decode the length-emitted encoding here */
  while ((ptr = (const uchar *)reader->read(RDB_ESCAPE_LENGTH))) {
    uint used_bytes;

    /* See pack_with_varchar_encoding. */
    if (use_legacy_format) {
      used_bytes = calc_unpack_legacy_variable_format(
          ptr[RDB_ESCAPE_LENGTH - 1], &finished);
    } else {
      used_bytes =
          calc_unpack_variable_format(ptr[RDB_ESCAPE_LENGTH - 1], &finished);
    }

    if (used_bytes == (uint)-1 || dst_len < used_bytes) {
      return HA_EXIT_FAILURE;  // Corruption in the data
    }

    if (finished) {
      break;
    }

    dst_len -= used_bytes;
  }

  if (!finished) {
    return HA_EXIT_FAILURE;
  }

  return HA_EXIT_SUCCESS;
}

const int VARCHAR_CMP_LESS_THAN_SPACES = 1;
const int VARCHAR_CMP_EQUAL_TO_SPACES = 2;
const int VARCHAR_CMP_GREATER_THAN_SPACES = 3;

/*
  Skip a keypart that uses Variable-Length Space-Padded encoding
*/

int Rdb_key_def::skip_variable_space_pad(
    const Rdb_field_packing *const fpi, const Field *const field,
    Rdb_string_reader *const reader) const {
  const uchar *ptr;
  bool finished = false;

  size_t dst_len = UINT_MAX; /* How much data can be there */

  if (field) {
    const Field_varstring *const field_var =
        static_cast<const Field_varstring *>(field);
    dst_len = field_var->pack_length() - field_var->length_bytes;
  }

  /* Decode the length-emitted encoding here */
  while ((ptr = (const uchar *)reader->read(fpi->m_segment_size))) {
    // See pack_with_varchar_space_pad
    const uchar c = ptr[fpi->m_segment_size - 1];
    if (c == VARCHAR_CMP_EQUAL_TO_SPACES) {
      // This is the last segment
      finished = true;
      break;
    } else if (c == VARCHAR_CMP_LESS_THAN_SPACES ||
               c == VARCHAR_CMP_GREATER_THAN_SPACES) {
      // This is not the last segment
      if ((fpi->m_segment_size - 1) > dst_len) {
        // The segment is full of data but the table field can't hold that
        // much! This must be data corruption.
        return HA_EXIT_FAILURE;
      }
      dst_len -= (fpi->m_segment_size - 1);
    } else {
      // Encountered a value that's none of the VARCHAR_CMP* constants
      // It's data corruption.
      return HA_EXIT_FAILURE;
    }
  }
  return finished ? HA_EXIT_SUCCESS : HA_EXIT_FAILURE;
}

/*
  Function of type rdb_index_field_unpack_t
*/

int Rdb_key_def::unpack_integer(
    Rdb_field_packing *const fpi, Field *const field, uchar *const to,
    Rdb_string_reader *const reader,
    Rdb_string_reader *const unp_reader MY_ATTRIBUTE((__unused__))) const {
  const int length = fpi->m_max_image_len;

  const uchar *from;
  if (!(from = (const uchar *)reader->read(length)))
    return UNPACK_FAILURE; /* Mem-comparable image doesn't have enough bytes */

#ifdef WORDS_BIGENDIAN
  {
    if (((Field_num *)field)->unsigned_flag)
      to[0] = from[0];
    else
      to[0] = (char)(from[0] ^ 128); // Reverse the sign bit.
    memcpy(to + 1, from + 1, length - 1);
  }
#else
  {
    const int sign_byte = from[0];
    if (((Field_num *)field)->unsigned_flag)
      to[length - 1] = sign_byte;
    else
      to[length - 1] =
          static_cast<char>(sign_byte ^ 128); // Reverse the sign bit.
    for (int i = 0, j = length - 1; i < length - 1; ++i, --j)
      to[i] = from[j];
  }
#endif
  return UNPACK_SUCCESS;
}

#if !defined(WORDS_BIGENDIAN)
static void rdb_swap_double_bytes(uchar *const dst, const uchar *const src) {
#if defined(__FLOAT_WORD_ORDER) && (__FLOAT_WORD_ORDER == __BIG_ENDIAN)
  // A few systems store the most-significant _word_ first on little-endian
  dst[0] = src[3];
  dst[1] = src[2];
  dst[2] = src[1];
  dst[3] = src[0];
  dst[4] = src[7];
  dst[5] = src[6];
  dst[6] = src[5];
  dst[7] = src[4];
#else
  dst[0] = src[7];
  dst[1] = src[6];
  dst[2] = src[5];
  dst[3] = src[4];
  dst[4] = src[3];
  dst[5] = src[2];
  dst[6] = src[1];
  dst[7] = src[0];
#endif
}

static void rdb_swap_float_bytes(uchar *const dst, const uchar *const src) {
  dst[0] = src[3];
  dst[1] = src[2];
  dst[2] = src[1];
  dst[3] = src[0];
}
#else
#define rdb_swap_double_bytes nullptr
#define rdb_swap_float_bytes nullptr
#endif

int Rdb_key_def::unpack_floating_point(
    uchar *const dst, Rdb_string_reader *const reader, const size_t &size,
    const int &exp_digit, const uchar *const zero_pattern,
    const uchar *const zero_val,
    void (*swap_func)(uchar *, const uchar *)) const {
  const uchar *const from = (const uchar *)reader->read(size);
  if (from == nullptr)
    return UNPACK_FAILURE; /* Mem-comparable image doesn't have enough bytes */

  /* Check to see if the value is zero */
  if (memcmp(from, zero_pattern, size) == 0) {
    memcpy(dst, zero_val, size);
    return UNPACK_SUCCESS;
  }

#if defined(WORDS_BIGENDIAN)
  // On big-endian, output can go directly into result
  uchar *const tmp = dst;
#else
  // Otherwise use a temporary buffer to make byte-swapping easier later
  uchar tmp[8];
#endif

  memcpy(tmp, from, size);

  if (tmp[0] & 0x80) {
    // If the high bit is set the original value was positive so
    // remove the high bit and subtract one from the exponent.
    ushort exp_part = ((ushort)tmp[0] << 8) | (ushort)tmp[1];
    exp_part &= 0x7FFF;                            // clear high bit;
    exp_part -= (ushort)1 << (16 - 1 - exp_digit); // subtract from exponent
    tmp[0] = (uchar)(exp_part >> 8);
    tmp[1] = (uchar)exp_part;
  } else {
    // Otherwise the original value was negative and all bytes have been
    // negated.
    for (size_t ii = 0; ii < size; ii++)
      tmp[ii] ^= 0xFF;
  }

#if !defined(WORDS_BIGENDIAN)
  // On little-endian, swap the bytes around
  swap_func(dst, tmp);
#else
  DBUG_ASSERT(swap_func == nullptr);
#endif

  return UNPACK_SUCCESS;
}

#if !defined(DBL_EXP_DIG)
#define DBL_EXP_DIG (sizeof(double) * 8 - DBL_MANT_DIG)
#endif

/*
  Function of type rdb_index_field_unpack_t

  Unpack a double by doing the reverse action of change_double_for_sort
  (sql/filesort.cc).  Note that this only works on IEEE values.
  Note also that this code assumes that NaN and +/-Infinity are never
  allowed in the database.
*/
int Rdb_key_def::unpack_double(
    Rdb_field_packing *const fpi MY_ATTRIBUTE((__unused__)),
    Field *const field MY_ATTRIBUTE((__unused__)), uchar *const field_ptr,
    Rdb_string_reader *const reader,
    Rdb_string_reader *const unp_reader MY_ATTRIBUTE((__unused__))) const {
  static double zero_val = 0.0;
  static const uchar zero_pattern[8] = {128, 0, 0, 0, 0, 0, 0, 0};

  return unpack_floating_point(field_ptr, reader, sizeof(double), DBL_EXP_DIG,
                               zero_pattern, (const uchar *)&zero_val,
                               rdb_swap_double_bytes);
}

#if !defined(FLT_EXP_DIG)
#define FLT_EXP_DIG (sizeof(float) * 8 - FLT_MANT_DIG)
#endif

/*
  Function of type rdb_index_field_unpack_t

  Unpack a float by doing the reverse action of Field_float::make_sort_key
  (sql/field.cc).  Note that this only works on IEEE values.
  Note also that this code assumes that NaN and +/-Infinity are never
  allowed in the database.
*/
int Rdb_key_def::unpack_float(
    Rdb_field_packing *const fpi, Field *const field MY_ATTRIBUTE((__unused__)),
    uchar *const field_ptr, Rdb_string_reader *const reader,
    Rdb_string_reader *const unp_reader MY_ATTRIBUTE((__unused__))) const {
  static float zero_val = 0.0;
  static const uchar zero_pattern[4] = {128, 0, 0, 0};

  return unpack_floating_point(field_ptr, reader, sizeof(float), FLT_EXP_DIG,
                               zero_pattern, (const uchar *)&zero_val,
                               rdb_swap_float_bytes);
}

/*
  Function of type rdb_index_field_unpack_t used to
  Unpack by doing the reverse action to Field_newdate::make_sort_key.
*/

int Rdb_key_def::unpack_newdate(
    Rdb_field_packing *const fpi, Field *const field MY_ATTRIBUTE((__unused__)),
    uchar *const field_ptr, Rdb_string_reader *const reader,
    Rdb_string_reader *const unp_reader MY_ATTRIBUTE((__unused__))) const {
  const char *from;
  DBUG_ASSERT(fpi->m_max_image_len == 3);

  if (!(from = reader->read(3)))
    return UNPACK_FAILURE; /* Mem-comparable image doesn't have enough bytes */

  field_ptr[0] = from[2];
  field_ptr[1] = from[1];
  field_ptr[2] = from[0];
  return UNPACK_SUCCESS;
}

/*
  Function of type rdb_index_field_unpack_t, used to
  Unpack the string by copying it over.
  This is for BINARY(n) where the value occupies the whole length.
*/

int Rdb_key_def::unpack_binary_str(
    Rdb_field_packing *const fpi, Field *const field, uchar *const to,
    Rdb_string_reader *const reader,
    Rdb_string_reader *const unp_reader MY_ATTRIBUTE((__unused__))) const {
  const char *from;
  if (!(from = reader->read(fpi->m_max_image_len)))
    return UNPACK_FAILURE; /* Mem-comparable image doesn't have enough bytes */

  memcpy(to, from, fpi->m_max_image_len);
  return UNPACK_SUCCESS;
}

/*
  Function of type rdb_index_field_unpack_t.
  For UTF-8, we need to convert 2-byte wide-character entities back into
  UTF8 sequences.
*/

int Rdb_key_def::unpack_utf8_str(
    Rdb_field_packing *const fpi, Field *const field, uchar *dst,
    Rdb_string_reader *const reader,
    Rdb_string_reader *const unp_reader MY_ATTRIBUTE((__unused__))) const {
  my_core::CHARSET_INFO *const cset = (my_core::CHARSET_INFO *)field->charset();
  const uchar *src;
  if (!(src = (const uchar *)reader->read(fpi->m_max_image_len)))
    return UNPACK_FAILURE; /* Mem-comparable image doesn't have enough bytes */

  const uchar *const src_end = src + fpi->m_max_image_len;
  uchar *const dst_end = dst + field->pack_length();

  while (src < src_end) {
    my_wc_t wc = (src[0] << 8) | src[1];
    src += 2;
    int res = cset->cset->wc_mb(cset, wc, dst, dst_end);
    DBUG_ASSERT(res > 0 && res <= 3);
    if (res < 0)
      return UNPACK_FAILURE;
    dst += res;
  }

  cset->cset->fill(cset, reinterpret_cast<char *>(dst), dst_end - dst,
                   cset->pad_char);
  return UNPACK_SUCCESS;
}

/*
  This is the original algorithm to encode a variable binary field.  It
  sets a flag byte every Nth byte.  The flag value is (255 - #pad) where
  #pad is the number of padding bytes that were needed (0 if all N-1
  bytes were used).

  If N=8 and the field is:
  * 3 bytes (1, 2, 3) this is encoded as: 1, 2, 3, 0, 0, 0, 0, 251
  * 4 bytes (1, 2, 3, 0) this is encoded as: 1, 2, 3, 0, 0, 0, 0, 252
  And the 4 byte string compares as greater than the 3 byte string

  Unfortunately the algorithm has a flaw.  If the input is exactly a
  multiple of N-1, an extra N bytes are written.  Since we usually use
  N=9, an 8 byte input will generate 18 bytes of output instead of the
  9 bytes of output that is optimal.

  See pack_variable_format for the newer algorithm.
*/
void Rdb_key_def::pack_legacy_variable_format(
    const uchar *src,   // The data to encode
    size_t src_len,     // The length of the data to encode
    uchar **dst) const  // The location to encode the data
{
  size_t copy_len;
  size_t padding_bytes;
  uchar *ptr = *dst;

  do {
    copy_len = std::min((size_t)RDB_LEGACY_ESCAPE_LENGTH - 1, src_len);
    padding_bytes = RDB_LEGACY_ESCAPE_LENGTH - 1 - copy_len;
    memcpy(ptr, src, copy_len);
    ptr += copy_len;
    src += copy_len;
    // pad with zeros if necessary
    if (padding_bytes > 0) {
      memset(ptr, 0, padding_bytes);
      ptr += padding_bytes;
    }

    *(ptr++) = 255 - padding_bytes;

    src_len -= copy_len;
  } while (padding_bytes == 0);

  *dst = ptr;
}

/*
  This is the new algorithm.  Similarly to the legacy format the input
  is split up into N-1 bytes and a flag byte is used as the Nth byte
  in the output.

  - If the previous segment needed any padding the flag is set to the
    number of bytes used (0..N-2).  0 is possible in the first segment
    if the input is 0 bytes long.
  - If no padding was used and there is no more data left in the input
    the flag is set to N-1
  - If no padding was used and there is still data left in the input the
    flag is set to N.

  For N=9, the following input values encode to the specified
  outout (where 'X' indicates a byte of the original input):
  - 0 bytes  is encoded as 0 0 0 0 0 0 0 0 0
  - 1 byte   is encoded as X 0 0 0 0 0 0 0 1
  - 2 bytes  is encoded as X X 0 0 0 0 0 0 2
  - 7 bytes  is encoded as X X X X X X X 0 7
  - 8 bytes  is encoded as X X X X X X X X 8
  - 9 bytes  is encoded as X X X X X X X X 9 X 0 0 0 0 0 0 0 1
  - 10 bytes is encoded as X X X X X X X X 9 X X 0 0 0 0 0 0 2
*/
void Rdb_key_def::pack_variable_format(
    const uchar *src,   // The data to encode
    size_t src_len,     // The length of the data to encode
    uchar **dst) const  // The location to encode the data
{
  uchar *ptr = *dst;

  for (;;) {
    // Figure out how many bytes to copy, copy them and adjust pointers
    const size_t copy_len = std::min((size_t)RDB_ESCAPE_LENGTH - 1, src_len);
    memcpy(ptr, src, copy_len);
    ptr += copy_len;
    src += copy_len;
    src_len -= copy_len;

    // Are we at the end of the input?
    if (src_len == 0) {
      // pad with zeros if necessary;
      const size_t padding_bytes = RDB_ESCAPE_LENGTH - 1 - copy_len;
      if (padding_bytes > 0) {
        memset(ptr, 0, padding_bytes);
        ptr += padding_bytes;
      }

      // Put the flag byte (0 - N-1) in the output
      *(ptr++) = (uchar)copy_len;
      break;
    }

    // We have more data - put the flag byte (N) in and continue
    *(ptr++) = RDB_ESCAPE_LENGTH;
  }

  *dst = ptr;
}

/*
  Function of type rdb_index_field_pack_t
*/

void Rdb_key_def::pack_with_varchar_encoding(
    Rdb_field_packing *const fpi, Field *const field, uchar *buf, uchar **dst,
    Rdb_pack_field_context *const pack_ctx MY_ATTRIBUTE((__unused__))) const {
  const CHARSET_INFO *const charset = field->charset();
  Field_varstring *const field_var = (Field_varstring *)field;

  const size_t value_length = (field_var->length_bytes == 1)
                                  ? (uint)*field->ptr
                                  : uint2korr(field->ptr);
  size_t xfrm_len = charset->coll->strnxfrm(
      charset, buf, fpi->m_max_image_len, field_var->char_length(),
      field_var->ptr + field_var->length_bytes, value_length, 0);

  /* Got a mem-comparable image in 'buf'. Now, produce varlength encoding */
  if (use_legacy_varbinary_format()) {
    pack_legacy_variable_format(buf, xfrm_len, dst);
  } else {
    pack_variable_format(buf, xfrm_len, dst);
  }
}

/*
  Compare the string in [buf..buf_end) with a string that is an infinite
  sequence of strings in space_xfrm
*/

static int
rdb_compare_string_with_spaces(const uchar *buf, const uchar *const buf_end,
                               const std::vector<uchar> *const space_xfrm) {
  int cmp = 0;
  while (buf < buf_end) {
    size_t bytes = std::min((size_t)(buf_end - buf), space_xfrm->size());
    if ((cmp = memcmp(buf, space_xfrm->data(), bytes)) != 0)
      break;
    buf += bytes;
  }
  return cmp;
}

static const int RDB_TRIMMED_CHARS_OFFSET = 8;
/*
  Pack the data with Variable-Length Space-Padded Encoding.

  The encoding is there to meet two goals:

  Goal#1. Comparison. The SQL standard says

    " If the collation for the comparison has the PAD SPACE characteristic,
    for the purposes of the comparison, the shorter value is effectively
    extended to the length of the longer by concatenation of <space>s on the
    right.

  At the moment, all MySQL collations except one have the PAD SPACE
  characteristic.  The exception is the "binary" collation that is used by
  [VAR]BINARY columns. (Note that binary collations for specific charsets,
  like utf8_bin or latin1_bin are not the same as "binary" collation, they have
  the PAD SPACE characteristic).

  Goal#2 is to preserve the number of trailing spaces in the original value.

  This is achieved by using the following encoding:
  The key part:
  - Stores mem-comparable image of the column
  - It is stored in chunks of fpi->m_segment_size bytes (*)
    = If the remainder of the chunk is not occupied, it is padded with mem-
      comparable image of the space character (cs->pad_char to be precise).
  - The last byte of the chunk shows how the rest of column's mem-comparable
    image would compare to mem-comparable image of the column extended with
    spaces. There are three possible values.
     - VARCHAR_CMP_LESS_THAN_SPACES,
     - VARCHAR_CMP_EQUAL_TO_SPACES
     - VARCHAR_CMP_GREATER_THAN_SPACES

  VARCHAR_CMP_EQUAL_TO_SPACES means that this chunk is the last one (the rest
  is spaces, or something that sorts as spaces, so there is no reason to store
  it).

  Example: if fpi->m_segment_size=5, and the collation is latin1_bin:

   'abcd\0'   => [ 'abcd' <VARCHAR_CMP_LESS> ]['\0    ' <VARCHAR_CMP_EQUAL> ]
   'abcd'     => [ 'abcd' <VARCHAR_CMP_EQUAL>]
   'abcd   '  => [ 'abcd' <VARCHAR_CMP_EQUAL>]
   'abcdZZZZ' => [ 'abcd' <VARCHAR_CMP_GREATER>][ 'ZZZZ' <VARCHAR_CMP_EQUAL>]

  As mentioned above, the last chunk is padded with mem-comparable images of
  cs->pad_char. It can be 1-byte long (latin1), 2 (utf8_bin), 3 (utf8mb4), etc.

  fpi->m_segment_size depends on the used collation. It is chosen to be such
  that no mem-comparable image of space will ever stretch across the segments
  (see get_segment_size_from_collation).

  == The value part (aka unpack_info) ==
  The value part stores the number of space characters that one needs to add
  when unpacking the string.
  - If the number is positive, it means add this many spaces at the end
  - If the number is negative, it means padding has added extra spaces which
    must be removed.

  Storage considerations
  - depending on column's max size, the number may occupy 1 or 2 bytes
  - the number of spaces that need to be removed is not more than
    RDB_TRIMMED_CHARS_OFFSET=8, so we offset the number by that value and
    then store it as unsigned.

  @seealso
    unpack_binary_or_utf8_varchar_space_pad
    unpack_simple_varchar_space_pad
    dummy_make_unpack_info
    skip_variable_space_pad
*/

void Rdb_key_def::pack_with_varchar_space_pad(
    Rdb_field_packing *const fpi, Field *const field, uchar *buf, uchar **dst,
    Rdb_pack_field_context *const pack_ctx) const {
  Rdb_string_writer *const unpack_info = pack_ctx->writer;
  const CHARSET_INFO *const charset = field->charset();
  const auto field_var = static_cast<Field_varstring *>(field);

  const size_t value_length = (field_var->length_bytes == 1)
                                  ? (uint)*field->ptr
                                  : uint2korr(field->ptr);

  const size_t trimmed_len = charset->cset->lengthsp(
      charset, (const char *)field_var->ptr + field_var->length_bytes,
      value_length);
  const size_t xfrm_len = charset->coll->strnxfrm(
      charset, buf, fpi->m_max_image_len, field_var->char_length(),
      field_var->ptr + field_var->length_bytes, trimmed_len, 0);

  /* Got a mem-comparable image in 'buf'. Now, produce varlength encoding */
  uchar *const buf_end = buf + xfrm_len;

  size_t encoded_size = 0;
  uchar *ptr = *dst;
  size_t padding_bytes;
  while (true) {
    const size_t copy_len =
        std::min<size_t>(fpi->m_segment_size - 1, buf_end - buf);
    padding_bytes = fpi->m_segment_size - 1 - copy_len;
    memcpy(ptr, buf, copy_len);
    ptr += copy_len;
    buf += copy_len;

    if (padding_bytes) {
      memcpy(ptr, fpi->space_xfrm->data(), padding_bytes);
      ptr += padding_bytes;
      *ptr = VARCHAR_CMP_EQUAL_TO_SPACES; // last segment
    } else {
      // Compare the string suffix with a hypothetical infinite string of
      // spaces. It could be that the first difference is beyond the end of
      // current chunk.
      const int cmp =
          rdb_compare_string_with_spaces(buf, buf_end, fpi->space_xfrm);

      if (cmp < 0)
        *ptr = VARCHAR_CMP_LESS_THAN_SPACES;
      else if (cmp > 0)
        *ptr = VARCHAR_CMP_GREATER_THAN_SPACES;
      else {
        // It turns out all the rest are spaces.
        *ptr = VARCHAR_CMP_EQUAL_TO_SPACES;
      }
    }
    encoded_size += fpi->m_segment_size;

    if (*(ptr++) == VARCHAR_CMP_EQUAL_TO_SPACES)
      break;
  }

  // m_unpack_info_stores_value means unpack_info stores the whole original
  // value. There is no need to store the number of trimmed/padded endspaces
  // in that case.
  if (unpack_info && !fpi->m_unpack_info_stores_value) {
    // (value_length - trimmed_len) is the number of trimmed space *characters*
    // then, padding_bytes is the number of *bytes* added as padding
    // then, we add 8, because we don't store negative values.
    DBUG_ASSERT(padding_bytes % fpi->space_xfrm_len == 0);
    DBUG_ASSERT((value_length - trimmed_len) % fpi->space_mb_len == 0);
    const size_t removed_chars =
        RDB_TRIMMED_CHARS_OFFSET +
        (value_length - trimmed_len) / fpi->space_mb_len -
        padding_bytes / fpi->space_xfrm_len;

    if (fpi->m_unpack_info_uses_two_bytes) {
      unpack_info->write_uint16(removed_chars);
    } else {
      DBUG_ASSERT(removed_chars < 0x100);
      unpack_info->write_uint8(removed_chars);
    }
  }

  *dst += encoded_size;
}

/*
  Calculate the number of used bytes in the chunk and whether this is the
  last chunk in the input.  This is based on the old legacy format - see
  pack_legacy_variable_format.
 */
uint Rdb_key_def::calc_unpack_legacy_variable_format(uchar flag,
                                                     bool *done) const {
  uint pad = 255 - flag;
  uint used_bytes = RDB_LEGACY_ESCAPE_LENGTH - 1 - pad;
  if (used_bytes > RDB_LEGACY_ESCAPE_LENGTH - 1) {
    return (uint)-1;
  }

  *done = used_bytes < RDB_LEGACY_ESCAPE_LENGTH - 1;
  return used_bytes;
}

/*
  Calculate the number of used bytes in the chunk and whether this is the
  last chunk in the input.  This is based on the new format - see
  pack_variable_format.
 */
uint Rdb_key_def::calc_unpack_variable_format(uchar flag, bool *done) const {
  // Check for invalid flag values
  if (flag > RDB_ESCAPE_LENGTH) {
    return (uint)-1;
  }

  // Values from 1 to N-1 indicate this is the last chunk and that is how
  // many bytes were used
  if (flag < RDB_ESCAPE_LENGTH) {
    *done = true;
    return flag;
  }

  // A value of N means we used N-1 bytes and had more to go
  *done = false;
  return RDB_ESCAPE_LENGTH - 1;
}

/*
  Unpack data that has charset information.  Each two bytes of the input is
  treated as a wide-character and converted to its multibyte equivalent in
  the output.
 */
static int
unpack_charset(const CHARSET_INFO *cset,  // character set information
               const uchar *src,          // source data to unpack
               uint src_len,              // length of source data
               uchar *dst,                // destination of unpacked data
               uint dst_len,              // length of destination data
               uint *used_bytes)          // output number of bytes used
{
  if (src_len & 1) {
    /*
      UTF-8 characters are encoded into two-byte entities. There is no way
      we can have an odd number of bytes after encoding.
    */
    return UNPACK_FAILURE;
  }

  uchar *dst_end = dst + dst_len;
  uint used = 0;

  for (uint ii = 0; ii < src_len; ii += 2) {
    my_wc_t wc = (src[ii] << 8) | src[ii + 1];
    int res = cset->cset->wc_mb(cset, wc, dst + used, dst_end);
    DBUG_ASSERT(res > 0 && res <= 3);
    if (res < 0) {
      return UNPACK_FAILURE;
    }

    used += res;
  }

  *used_bytes = used;
  return UNPACK_SUCCESS;
}

/*
  Function of type rdb_index_field_unpack_t
*/

int Rdb_key_def::unpack_binary_or_utf8_varchar(
    Rdb_field_packing *const fpi, Field *const field, uchar *dst,
    Rdb_string_reader *const reader,
    Rdb_string_reader *const unp_reader MY_ATTRIBUTE((__unused__))) const {
  const uchar *ptr;
  size_t len = 0;
  bool finished = false;
  uchar *d0 = dst;
  Field_varstring *const field_var = (Field_varstring *)field;
  dst += field_var->length_bytes;
  // How much we can unpack
  size_t dst_len = field_var->pack_length() - field_var->length_bytes;

  bool use_legacy_format = use_legacy_varbinary_format();

  /* Decode the length-emitted encoding here */
  while ((ptr = (const uchar *)reader->read(RDB_ESCAPE_LENGTH))) {
    uint used_bytes;

    /* See pack_with_varchar_encoding. */
    if (use_legacy_format) {
      used_bytes = calc_unpack_legacy_variable_format(
          ptr[RDB_ESCAPE_LENGTH - 1], &finished);
    } else {
      used_bytes =
          calc_unpack_variable_format(ptr[RDB_ESCAPE_LENGTH - 1], &finished);
    }

    if (used_bytes == (uint)-1 || dst_len < used_bytes) {
      return UNPACK_FAILURE;  // Corruption in the data
    }

    /*
      Now, we need to decode used_bytes of data and append them to the value.
    */
    if (fpi->m_varchar_charset->number == COLLATION_UTF8_BIN) {
      int err = unpack_charset(fpi->m_varchar_charset, ptr, used_bytes, dst,
                               dst_len, &used_bytes);
      if (err != UNPACK_SUCCESS) {
        return err;
      }
    } else {
      memcpy(dst, ptr, used_bytes);
    }

    dst += used_bytes;
    dst_len -= used_bytes;
    len += used_bytes;

    if (finished) {
      break;
    }
  }

  if (!finished) {
    return UNPACK_FAILURE;
  }

  /* Save the length */
  if (field_var->length_bytes == 1) {
    d0[0] = (uchar)len;
  } else {
    DBUG_ASSERT(field_var->length_bytes == 2);
    int2store(d0, len);
  }
  return UNPACK_SUCCESS;
}

/*
  @seealso
    pack_with_varchar_space_pad - packing function
    unpack_simple_varchar_space_pad - unpacking function for 'simple'
    charsets.
    skip_variable_space_pad - skip function
*/
int Rdb_key_def::unpack_binary_or_utf8_varchar_space_pad(
    Rdb_field_packing *const fpi, Field *const field, uchar *dst,
    Rdb_string_reader *const reader,
    Rdb_string_reader *const unp_reader) const {
  const uchar *ptr;
  size_t len = 0;
  bool finished = false;
  Field_varstring *const field_var = static_cast<Field_varstring *>(field);
  uchar *d0 = dst;
  uchar *dst_end = dst + field_var->pack_length();
  dst += field_var->length_bytes;

  uint space_padding_bytes = 0;
  uint extra_spaces;
  if ((fpi->m_unpack_info_uses_two_bytes
           ? unp_reader->read_uint16(&extra_spaces)
           : unp_reader->read_uint8(&extra_spaces))) {
    return UNPACK_FAILURE;
  }

  if (extra_spaces <= RDB_TRIMMED_CHARS_OFFSET) {
    space_padding_bytes =
        -(static_cast<int>(extra_spaces) - RDB_TRIMMED_CHARS_OFFSET);
    extra_spaces = 0;
  } else
    extra_spaces -= RDB_TRIMMED_CHARS_OFFSET;

  space_padding_bytes *= fpi->space_xfrm_len;

  /* Decode the length-emitted encoding here */
  while ((ptr = (const uchar *)reader->read(fpi->m_segment_size))) {
    const char last_byte = ptr[fpi->m_segment_size - 1];
    size_t used_bytes;
    if (last_byte == VARCHAR_CMP_EQUAL_TO_SPACES) // this is the last segment
    {
      if (space_padding_bytes > (fpi->m_segment_size - 1))
        return UNPACK_FAILURE; // Cannot happen, corrupted data
      used_bytes = (fpi->m_segment_size - 1) - space_padding_bytes;
      finished = true;
    } else {
      if (last_byte != VARCHAR_CMP_LESS_THAN_SPACES &&
          last_byte != VARCHAR_CMP_GREATER_THAN_SPACES) {
        return UNPACK_FAILURE; // Invalid value
      }
      used_bytes = fpi->m_segment_size - 1;
    }

    // Now, need to decode used_bytes of data and append them to the value.
    if (fpi->m_varchar_charset->number == COLLATION_UTF8_BIN) {
      if (used_bytes & 1) {
        /*
          UTF-8 characters are encoded into two-byte entities. There is no way
          we can have an odd number of bytes after encoding.
        */
        return UNPACK_FAILURE;
      }

      const uchar *src = ptr;
      const uchar *const src_end = ptr + used_bytes;
      while (src < src_end) {
        my_wc_t wc = (src[0] << 8) | src[1];
        src += 2;
        const CHARSET_INFO *cset = fpi->m_varchar_charset;
        int res = cset->cset->wc_mb(cset, wc, dst, dst_end);
        DBUG_ASSERT(res <= 3);
        if (res <= 0)
          return UNPACK_FAILURE;
        dst += res;
        len += res;
      }
    } else {
      if (dst + used_bytes > dst_end)
        return UNPACK_FAILURE;
      memcpy(dst, ptr, used_bytes);
      dst += used_bytes;
      len += used_bytes;
    }

    if (finished) {
      if (extra_spaces) {
        // Both binary and UTF-8 charset store space as ' ',
        // so the following is ok:
        if (dst + extra_spaces > dst_end)
          return UNPACK_FAILURE;
        memset(dst, fpi->m_varchar_charset->pad_char, extra_spaces);
        len += extra_spaces;
      }
      break;
    }
  }

  if (!finished)
    return UNPACK_FAILURE;

  /* Save the length */
  if (field_var->length_bytes == 1) {
    d0[0] = (uchar)len;
  } else {
    DBUG_ASSERT(field_var->length_bytes == 2);
    int2store(d0, len);
  }
  return UNPACK_SUCCESS;
}

/////////////////////////////////////////////////////////////////////////

/*
  Function of type rdb_make_unpack_info_t
*/

void Rdb_key_def::make_unpack_unknown(
    const Rdb_collation_codec *codec MY_ATTRIBUTE((__unused__)),
    const Field *const field, Rdb_pack_field_context *const pack_ctx) const {
  pack_ctx->writer->write(field->ptr, field->pack_length());
}

/*
  This point of this function is only to indicate that unpack_info is
  available.

  The actual unpack_info data is produced by the function that packs the key,
  that is, pack_with_varchar_space_pad.
*/

void Rdb_key_def::dummy_make_unpack_info(
    const Rdb_collation_codec *codec MY_ATTRIBUTE((__unused__)),
    const Field *field MY_ATTRIBUTE((__unused__)),
    Rdb_pack_field_context *pack_ctx MY_ATTRIBUTE((__unused__))) const {
  // Do nothing
}

/*
  Function of type rdb_index_field_unpack_t
*/

int Rdb_key_def::unpack_unknown(Rdb_field_packing *const fpi,
                                Field *const field, uchar *const dst,
                                Rdb_string_reader *const reader,
                                Rdb_string_reader *const unp_reader) const {
  const uchar *ptr;
  const uint len = fpi->m_unpack_data_len;
  // We don't use anything from the key, so skip over it.
  if (skip_max_length(fpi, field, reader)) {
    return UNPACK_FAILURE;
  }

  DBUG_ASSERT_IMP(len > 0, unp_reader != nullptr);

  if ((ptr = (const uchar *)unp_reader->read(len))) {
    memcpy(dst, ptr, len);
    return UNPACK_SUCCESS;
  }
  return UNPACK_FAILURE;
}

/*
  Function of type rdb_make_unpack_info_t
*/

void Rdb_key_def::make_unpack_unknown_varchar(
    const Rdb_collation_codec *const codec MY_ATTRIBUTE((__unused__)),
    const Field *const field, Rdb_pack_field_context *const pack_ctx) const {
  const auto f = static_cast<const Field_varstring *>(field);
  uint len = f->length_bytes == 1 ? (uint)*f->ptr : uint2korr(f->ptr);
  len += f->length_bytes;
  pack_ctx->writer->write(field->ptr, len);
}

/*
  Function of type rdb_index_field_unpack_t

  @detail
  Unpack a key part in an "unknown" collation from its
  (mem_comparable_form, unpack_info) form.

  "Unknown" means we have no clue about how mem_comparable_form is made from
  the original string, so we keep the whole original string in the unpack_info.

  @seealso
    make_unpack_unknown, unpack_unknown
*/

int Rdb_key_def::unpack_unknown_varchar(
    Rdb_field_packing *const fpi, Field *const field, uchar *dst,
    Rdb_string_reader *const reader,
    Rdb_string_reader *const unp_reader) const {
  const uchar *ptr;
  uchar *const d0 = dst;
  const auto f = static_cast<Field_varstring *>(field);
  dst += f->length_bytes;
  const uint len_bytes = f->length_bytes;
  // We don't use anything from the key, so skip over it.
  if ((this->*fpi->m_skip_func)(fpi, field, reader)) {
    return UNPACK_FAILURE;
  }

  DBUG_ASSERT(len_bytes > 0);
  DBUG_ASSERT(unp_reader != nullptr);

  if ((ptr = (const uchar *)unp_reader->read(len_bytes))) {
    memcpy(d0, ptr, len_bytes);
    const uint len = len_bytes == 1 ? (uint)*ptr : uint2korr(ptr);
    if ((ptr = (const uchar *)unp_reader->read(len))) {
      memcpy(dst, ptr, len);
      return UNPACK_SUCCESS;
    }
  }
  return UNPACK_FAILURE;
}

/*
  Write unpack_data for a "simple" collation
*/
static void rdb_write_unpack_simple(Rdb_bit_writer *const writer,
                                    const Rdb_collation_codec *const codec,
                                    const uchar *const src,
                                    const size_t src_len) {
  for (uint i = 0; i < src_len; i++) {
    writer->write(codec->m_enc_size[src[i]], codec->m_enc_idx[src[i]]);
  }
}

static uint rdb_read_unpack_simple(Rdb_bit_reader *const reader,
                                   const Rdb_collation_codec *const codec,
                                   const uchar *const src,
                                   const size_t &src_len, uchar *const dst) {
  for (uint i = 0; i < src_len; i++) {
    if (codec->m_dec_size[src[i]] > 0) {
      uint *ret;
      DBUG_ASSERT(reader != nullptr);

      if ((ret = reader->read(codec->m_dec_size[src[i]])) == nullptr) {
        return UNPACK_FAILURE;
      }
      dst[i] = codec->m_dec_idx[*ret][src[i]];
    } else {
      dst[i] = codec->m_dec_idx[0][src[i]];
    }
  }

  return UNPACK_SUCCESS;
}

/*
  Function of type rdb_make_unpack_info_t

  @detail
    Make unpack_data for VARCHAR(n) in a "simple" charset.
*/

void Rdb_key_def::make_unpack_simple_varchar(
    const Rdb_collation_codec *const codec, const Field *const field,
    Rdb_pack_field_context *const pack_ctx) const {
  const auto f = static_cast<const Field_varstring *>(field);
  uchar *const src = f->ptr + f->length_bytes;
  const size_t src_len =
      f->length_bytes == 1 ? (uint)*f->ptr : uint2korr(f->ptr);
  Rdb_bit_writer bit_writer(pack_ctx->writer);
  // The std::min compares characters with bytes, but for simple collations,
  // mbmaxlen = 1.
  rdb_write_unpack_simple(&bit_writer, codec, src,
                          std::min((size_t)f->char_length(), src_len));
}

/*
  Function of type rdb_index_field_unpack_t

  @seealso
    pack_with_varchar_space_pad - packing function
    unpack_binary_or_utf8_varchar_space_pad - a similar unpacking function
*/

int Rdb_key_def::unpack_simple_varchar_space_pad(
    Rdb_field_packing *const fpi, Field *const field, uchar *dst,
    Rdb_string_reader *const reader,
    Rdb_string_reader *const unp_reader) const {
  const uchar *ptr;
  size_t len = 0;
  bool finished = false;
  uchar *d0 = dst;
  const Field_varstring *const field_var =
      static_cast<Field_varstring *>(field);
  // For simple collations, char_length is also number of bytes.
  DBUG_ASSERT((size_t)fpi->m_max_image_len >= field_var->char_length());
  uchar *dst_end = dst + field_var->pack_length();
  dst += field_var->length_bytes;
  Rdb_bit_reader bit_reader(unp_reader);

  uint space_padding_bytes = 0;
  uint extra_spaces;
  DBUG_ASSERT(unp_reader != nullptr);

  if ((fpi->m_unpack_info_uses_two_bytes
           ? unp_reader->read_uint16(&extra_spaces)
           : unp_reader->read_uint8(&extra_spaces))) {
    return UNPACK_FAILURE;
  }

  if (extra_spaces <= 8) {
    space_padding_bytes = -(static_cast<int>(extra_spaces) - 8);
    extra_spaces = 0;
  } else
    extra_spaces -= 8;

  space_padding_bytes *= fpi->space_xfrm_len;

  /* Decode the length-emitted encoding here */
  while ((ptr = (const uchar *)reader->read(fpi->m_segment_size))) {
    const char last_byte =
        ptr[fpi->m_segment_size - 1]; // number of padding bytes
    size_t used_bytes;
    if (last_byte == VARCHAR_CMP_EQUAL_TO_SPACES) {
      // this is the last one
      if (space_padding_bytes > (fpi->m_segment_size - 1))
        return UNPACK_FAILURE; // Cannot happen, corrupted data
      used_bytes = (fpi->m_segment_size - 1) - space_padding_bytes;
      finished = true;
    } else {
      if (last_byte != VARCHAR_CMP_LESS_THAN_SPACES &&
          last_byte != VARCHAR_CMP_GREATER_THAN_SPACES) {
        return UNPACK_FAILURE;
      }
      used_bytes = fpi->m_segment_size - 1;
    }

    if (dst + used_bytes > dst_end) {
      // The value on disk is longer than the field definition allows?
      return UNPACK_FAILURE;
    }

    uint ret;
    if ((ret = rdb_read_unpack_simple(&bit_reader, fpi->m_charset_codec, ptr,
                                      used_bytes, dst)) != UNPACK_SUCCESS) {
      return ret;
    }

    dst += used_bytes;
    len += used_bytes;

    if (finished) {
      if (extra_spaces) {
        if (dst + extra_spaces > dst_end)
          return UNPACK_FAILURE;
        // pad_char has a 1-byte form in all charsets that
        // are handled by rdb_init_collation_mapping.
        memset(dst, field_var->charset()->pad_char, extra_spaces);
        len += extra_spaces;
      }
      break;
    }
  }

  if (!finished)
    return UNPACK_FAILURE;

  /* Save the length */
  if (field_var->length_bytes == 1) {
    d0[0] = (uchar)len;
  } else {
    DBUG_ASSERT(field_var->length_bytes == 2);
    int2store(d0, len);
  }
  return UNPACK_SUCCESS;
}

/*
  Function of type rdb_make_unpack_info_t

  @detail
    Make unpack_data for CHAR(n) value in a "simple" charset.
    It is CHAR(N), so SQL layer has padded the value with spaces up to N chars.

  @seealso
    The VARCHAR variant is in make_unpack_simple_varchar
*/

void Rdb_key_def::make_unpack_simple(
    const Rdb_collation_codec *const codec, const Field *const field,
    Rdb_pack_field_context *const pack_ctx) const {
  const uchar *const src = field->ptr;
  Rdb_bit_writer bit_writer(pack_ctx->writer);
  rdb_write_unpack_simple(&bit_writer, codec, src, field->pack_length());
}

/*
  Function of type rdb_index_field_unpack_t
*/

int Rdb_key_def::unpack_simple(Rdb_field_packing *const fpi,
                               Field *const field MY_ATTRIBUTE((__unused__)),
                               uchar *const dst,
                               Rdb_string_reader *const reader,
                               Rdb_string_reader *const unp_reader) const {
  const uchar *ptr;
  const uint len = fpi->m_max_image_len;
  Rdb_bit_reader bit_reader(unp_reader);

  if (!(ptr = (const uchar *)reader->read(len))) {
    return UNPACK_FAILURE;
  }

  return rdb_read_unpack_simple(unp_reader ? &bit_reader : nullptr,
                                fpi->m_charset_codec, ptr, len, dst);
}

// See Rdb_charset_space_info::spaces_xfrm
const int RDB_SPACE_XFRM_SIZE = 32;

// A class holding information about how space character is represented in a
// charset.
class Rdb_charset_space_info {
public:
  Rdb_charset_space_info(const Rdb_charset_space_info &) = delete;
  Rdb_charset_space_info &operator=(const Rdb_charset_space_info &) = delete;
  Rdb_charset_space_info() = default;

  // A few strxfrm'ed space characters, at least RDB_SPACE_XFRM_SIZE bytes
  std::vector<uchar> spaces_xfrm;

  // length(strxfrm(' '))
  size_t space_xfrm_len;

  // length of the space character itself
  // Typically space is just 0x20 (length=1) but in ucs2 it is 0x00 0x20
  // (length=2)
  size_t space_mb_len;
};

static std::array<std::unique_ptr<Rdb_charset_space_info>, MY_ALL_CHARSETS_SIZE>
    rdb_mem_comparable_space;

/*
  @brief
  For a given charset, get
   - strxfrm('    '), a sample that is at least RDB_SPACE_XFRM_SIZE bytes long.
   - length of strxfrm(charset, ' ')
   - length of the space character in the charset

  @param cs  IN    Charset to get the space for
  @param ptr OUT   A few space characters
  @param len OUT   Return length of the space (in bytes)

  @detail
    It is tempting to pre-generate mem-comparable form of space character for
    every charset on server startup.
    One can't do that: some charsets are not initialized until somebody
    attempts to use them (e.g. create or open a table that has a field that
    uses the charset).
*/

static void rdb_get_mem_comparable_space(const CHARSET_INFO *const cs,
                                         const std::vector<uchar> **xfrm,
                                         size_t *const xfrm_len,
                                         size_t *const mb_len) {
  DBUG_ASSERT(cs->number < MY_ALL_CHARSETS_SIZE);
  if (!rdb_mem_comparable_space[cs->number].get()) {
    RDB_MUTEX_LOCK_CHECK(rdb_mem_cmp_space_mutex);
    if (!rdb_mem_comparable_space[cs->number].get()) {
      // Upper bound of how many bytes can be occupied by multi-byte form of a
      // character in any charset.
      const int MAX_MULTI_BYTE_CHAR_SIZE = 4;
      DBUG_ASSERT(cs->mbmaxlen <= MAX_MULTI_BYTE_CHAR_SIZE);

      // multi-byte form of the ' ' (space) character
      uchar space_mb[MAX_MULTI_BYTE_CHAR_SIZE];

      const size_t space_mb_len = cs->cset->wc_mb(
          cs, (my_wc_t)cs->pad_char, space_mb, space_mb + sizeof(space_mb));

      uchar space[20]; // mem-comparable image of the space character

      const size_t space_len = cs->coll->strnxfrm(cs, space, sizeof(space), 1,
                                                  space_mb, space_mb_len, 0);
      Rdb_charset_space_info *const info = new Rdb_charset_space_info;
      info->space_xfrm_len = space_len;
      info->space_mb_len = space_mb_len;
      while (info->spaces_xfrm.size() < RDB_SPACE_XFRM_SIZE) {
        info->spaces_xfrm.insert(info->spaces_xfrm.end(), space,
                                 space + space_len);
      }
      rdb_mem_comparable_space[cs->number].reset(info);
    }
    RDB_MUTEX_UNLOCK_CHECK(rdb_mem_cmp_space_mutex);
  }

  *xfrm = &rdb_mem_comparable_space[cs->number]->spaces_xfrm;
  *xfrm_len = rdb_mem_comparable_space[cs->number]->space_xfrm_len;
  *mb_len = rdb_mem_comparable_space[cs->number]->space_mb_len;
}

mysql_mutex_t rdb_mem_cmp_space_mutex;

std::array<const Rdb_collation_codec *, MY_ALL_CHARSETS_SIZE>
    rdb_collation_data;
mysql_mutex_t rdb_collation_data_mutex;

static bool rdb_is_collation_supported(const my_core::CHARSET_INFO *const cs) {
  return cs->strxfrm_multiply==1 && cs->mbmaxlen == 1 &&
         !(cs->state & (MY_CS_BINSORT | MY_CS_NOPAD));
}

static const Rdb_collation_codec *
rdb_init_collation_mapping(const my_core::CHARSET_INFO *const cs) {
  DBUG_ASSERT(cs && cs->state & MY_CS_AVAILABLE);
  const Rdb_collation_codec *codec = rdb_collation_data[cs->number];

  if (codec == nullptr && rdb_is_collation_supported(cs)) {
    RDB_MUTEX_LOCK_CHECK(rdb_collation_data_mutex);

    codec = rdb_collation_data[cs->number];
    if (codec == nullptr) {
      Rdb_collation_codec *cur = nullptr;

      // Compute reverse mapping for simple collations.
      if (rdb_is_collation_supported(cs)) {
        cur = new Rdb_collation_codec;
        std::map<uchar, std::vector<uchar>> rev_map;
        size_t max_conflict_size = 0;
        for (int src = 0; src < 256; src++) {
          uchar dst = cs->sort_order[src];
          rev_map[dst].push_back(src);
          max_conflict_size = std::max(max_conflict_size, rev_map[dst].size());
        }
        cur->m_dec_idx.resize(max_conflict_size);

        for (auto const &p : rev_map) {
          uchar dst = p.first;
          for (uint idx = 0; idx < p.second.size(); idx++) {
            uchar src = p.second[idx];
            uchar bits =
                my_bit_log2(my_round_up_to_next_power(p.second.size()));
            cur->m_enc_idx[src] = idx;
            cur->m_enc_size[src] = bits;
            cur->m_dec_size[dst] = bits;
            cur->m_dec_idx[idx][dst] = src;
          }
        }

        cur->m_make_unpack_info_func = {
            &Rdb_key_def::make_unpack_simple_varchar,
            &Rdb_key_def::make_unpack_simple};
        cur->m_unpack_func = {&Rdb_key_def::unpack_simple_varchar_space_pad,
                              &Rdb_key_def::unpack_simple};
      } else {
        // Out of luck for now.
      }

      if (cur != nullptr) {
        codec = cur;
        cur->m_cs = cs;
        rdb_collation_data[cs->number] = cur;
      }
    }

    RDB_MUTEX_UNLOCK_CHECK(rdb_collation_data_mutex);
  }

  return codec;
}

static int get_segment_size_from_collation(const CHARSET_INFO *const cs) {
  int ret;
  if (cs->number == COLLATION_UTF8MB4_BIN || cs->number == COLLATION_UTF16_BIN ||
      cs->number == COLLATION_UTF16LE_BIN || cs->number == COLLATION_UTF32_BIN) {
    /*
      In these collations, a character produces one weight, which is 3 bytes.
      Segment has 3 characters, add one byte for VARCHAR_CMP_* marker, and we
      get 3*3+1=10
    */
    ret = 10;
  } else {
    /*
      All other collations. There are two classes:
      - Unicode-based, except for collations mentioned in the if-condition.
        For these all weights are 2 bytes long, a character may produce 0..8
        weights.
        in any case, 8 bytes of payload in the segment guarantee that the last
        space character won't span across segments.

      - Collations not based on unicode. These have length(strxfrm(' '))=1,
        there nothing to worry about.

      In both cases, take 8 bytes payload + 1 byte for VARCHAR_CMP* marker.
    */
    ret = 9;
  }
  DBUG_ASSERT(ret < RDB_SPACE_XFRM_SIZE);
  return ret;
}

/*
  @brief
    Setup packing of index field into its mem-comparable form

  @detail
    - It is possible produce mem-comparable form for any datatype.
    - Some datatypes also allow to unpack the original value from its
      mem-comparable form.
      = Some of these require extra information to be stored in "unpack_info".
        unpack_info is not a part of mem-comparable form, it is only used to
        restore the original value

  @param
    field  IN  field to be packed/un-packed

  @return
    TRUE  -  Field can be read with index-only reads
    FALSE -  Otherwise
*/

bool Rdb_field_packing::setup(const Rdb_key_def *const key_descr,
                              const Field *const field, const uint &keynr_arg,
                              const uint &key_part_arg,
                              const uint16 &key_length) {
  int res = false;
  enum_field_types type = field ? field->real_type() : MYSQL_TYPE_LONGLONG;

  m_keynr = keynr_arg;
  m_key_part = key_part_arg;

  m_maybe_null = field ? field->real_maybe_null() : false;
  m_unpack_func = nullptr;
  m_make_unpack_info_func = nullptr;
  m_unpack_data_len = 0;
  space_xfrm = nullptr; // safety

  /* Calculate image length. By default, is is pack_length() */
  m_max_image_len =
      field ? field->pack_length() : ROCKSDB_SIZEOF_HIDDEN_PK_COLUMN;
  m_skip_func = &Rdb_key_def::skip_max_length;
  m_pack_func = &Rdb_key_def::pack_with_make_sort_key;

  switch (type) {
  case MYSQL_TYPE_LONGLONG:
  case MYSQL_TYPE_LONG:
  case MYSQL_TYPE_INT24:
  case MYSQL_TYPE_SHORT:
  case MYSQL_TYPE_TINY:
    m_unpack_func = &Rdb_key_def::unpack_integer;
    return true;

  case MYSQL_TYPE_DOUBLE:
    m_unpack_func = &Rdb_key_def::unpack_double;
    return true;

  case MYSQL_TYPE_FLOAT:
    m_unpack_func = &Rdb_key_def::unpack_float;
    return true;

  case MYSQL_TYPE_NEWDECIMAL:
  /*
    Decimal is packed with Field_new_decimal::make_sort_key, which just
    does memcpy.
    Unpacking decimal values was supported only after fix for issue#253,
    because of that ha_rocksdb::get_storage_type() handles decimal values
    in a special way.
  */
  case MYSQL_TYPE_DATETIME2:
  case MYSQL_TYPE_TIMESTAMP2:
  /* These are packed with Field_temporal_with_date_and_timef::make_sort_key */
  case MYSQL_TYPE_TIME2: /* TIME is packed with Field_timef::make_sort_key */
  case MYSQL_TYPE_YEAR:  /* YEAR is packed with  Field_tiny::make_sort_key */
    /* Everything that comes here is packed with just a memcpy(). */
    m_unpack_func = &Rdb_key_def::unpack_binary_str;
    return true;

  case MYSQL_TYPE_NEWDATE:
    /*
      This is packed by Field_newdate::make_sort_key. It assumes the data is
      3 bytes, and packing is done by swapping the byte order (for both big-
      and little-endian)
    */
    m_unpack_func = &Rdb_key_def::unpack_newdate;
    return true;
  case MYSQL_TYPE_TINY_BLOB:
  case MYSQL_TYPE_MEDIUM_BLOB:
  case MYSQL_TYPE_LONG_BLOB:
  case MYSQL_TYPE_BLOB: {
    if (key_descr) {
      // The my_charset_bin collation is special in that it will consider
      // shorter strings sorting as less than longer strings.
      //
      // See Field_blob::make_sort_key for details.
      m_max_image_len =
          key_length + (field->charset()->number == COLLATION_BINARY
                            ? reinterpret_cast<const Field_blob *>(field)
                                  ->pack_length_no_ptr()
                            : 0);
      // Return false because indexes on text/blob will always require
      // a prefix. With a prefix, the optimizer will not be able to do an
      // index-only scan since there may be content occuring after the prefix
      // length.
      return false;
    }
  }
  default:
    break;
  }

  m_unpack_info_stores_value = false;
  /* Handle [VAR](CHAR|BINARY) */

  if (type == MYSQL_TYPE_VARCHAR || type == MYSQL_TYPE_STRING) {
    /*
      For CHAR-based columns, check how strxfrm image will take.
      field->field_length = field->char_length() * cs->mbmaxlen.
    */
    const CHARSET_INFO *cs = field->charset();
    m_max_image_len = cs->coll->strnxfrmlen(cs, field->field_length);
  }
  const bool is_varchar = (type == MYSQL_TYPE_VARCHAR);
  const CHARSET_INFO *cs = field->charset();
  // max_image_len before chunking is taken into account
  const int max_image_len_before_chunks = m_max_image_len;

  if (is_varchar) {
    // The default for varchar is variable-length, without space-padding for
    // comparisons
    m_varchar_charset = cs;
    m_skip_func = &Rdb_key_def::skip_variable_length;
    m_pack_func = &Rdb_key_def::pack_with_varchar_encoding;
    if (!key_descr || key_descr->use_legacy_varbinary_format()) {
      m_max_image_len = RDB_LEGACY_ENCODED_SIZE(m_max_image_len);
    } else {
      // Calculate the maximum size of the short section plus the
      // maximum size of the long section
      m_max_image_len = RDB_ENCODED_SIZE(m_max_image_len);
    }

    const auto field_var = static_cast<const Field_varstring *>(field);
    m_unpack_info_uses_two_bytes = (field_var->field_length + 8 >= 0x100);
  }

  if (type == MYSQL_TYPE_VARCHAR || type == MYSQL_TYPE_STRING) {
    // See http://dev.mysql.com/doc/refman/5.7/en/string-types.html for
    // information about character-based datatypes are compared.
    bool use_unknown_collation = false;
    DBUG_EXECUTE_IF("myrocks_enable_unknown_collation_index_only_scans",
                    use_unknown_collation = true;);

    if (cs->number == COLLATION_BINARY) {
      // - SQL layer pads BINARY(N) so that it always is N bytes long.
      // - For VARBINARY(N), values may have different lengths, so we're using
      //   variable-length encoding. This is also the only charset where the
      //   values are not space-padded for comparison.
      m_unpack_func = is_varchar ? &Rdb_key_def::unpack_binary_or_utf8_varchar
                                 : &Rdb_key_def::unpack_binary_str;
      res = true;
    } else if (cs->number == COLLATION_LATIN1_BIN || cs->number == COLLATION_UTF8_BIN) {
      // For _bin collations, mem-comparable form of the string is the string
      // itself.

      if (is_varchar) {
        // VARCHARs - are compared as if they were space-padded - but are
        // not actually space-padded (reading the value back produces the
        // original value, without the padding)
        m_unpack_func = &Rdb_key_def::unpack_binary_or_utf8_varchar_space_pad;
        m_skip_func = &Rdb_key_def::skip_variable_space_pad;
        m_pack_func = &Rdb_key_def::pack_with_varchar_space_pad;
        m_make_unpack_info_func = &Rdb_key_def::dummy_make_unpack_info;
        m_segment_size = get_segment_size_from_collation(cs);
        m_max_image_len =
            (max_image_len_before_chunks / (m_segment_size - 1) + 1) *
            m_segment_size;
        rdb_get_mem_comparable_space(cs, &space_xfrm, &space_xfrm_len,
                                     &space_mb_len);
      } else {
        // SQL layer pads CHAR(N) values to their maximum length.
        // We just store that and restore it back.
        m_unpack_func = (cs->number == COLLATION_LATIN1_BIN) ?
                              &Rdb_key_def::unpack_binary_str
                            : &Rdb_key_def::unpack_utf8_str;
      }
      res = true;
    } else {
      // This is [VAR]CHAR(n) and the collation is not $(charset_name)_bin

      res = true; // index-only scans are possible
      m_unpack_data_len = is_varchar ? 0 : field->field_length;
      const uint idx = is_varchar ? 0 : 1;
      const Rdb_collation_codec *codec = nullptr;

      if (is_varchar) {
        // VARCHAR requires space-padding for doing comparisons
        //
        // The check for cs->levels_for_order is to catch
        // latin2_czech_cs and cp1250_czech_cs - multi-level collations
        // that Variable-Length Space Padded Encoding can't handle.
        // It is not expected to work for any other multi-level collations,
        // either.
        // Currently we handle these collations as NO_PAD, even if they have
        // PAD_SPACE attribute.
        if (cs->levels_for_order == 1) {
          m_pack_func = &Rdb_key_def::pack_with_varchar_space_pad;
          m_skip_func = &Rdb_key_def::skip_variable_space_pad;
          m_segment_size = get_segment_size_from_collation(cs);
          m_max_image_len =
              (max_image_len_before_chunks / (m_segment_size - 1) + 1) *
              m_segment_size;
          rdb_get_mem_comparable_space(cs, &space_xfrm, &space_xfrm_len,
                                       &space_mb_len);
        } else {
          //  NO_LINT_DEBUG
          sql_print_warning("RocksDB: you're trying to create an index "
                            "with a multi-level collation %s",
                            cs->name);
          //  NO_LINT_DEBUG
          sql_print_warning("MyRocks will handle this collation internally "
                            " as if it had a NO_PAD attribute.");
          m_pack_func = &Rdb_key_def::pack_with_varchar_encoding;
          m_skip_func = &Rdb_key_def::skip_variable_length;
        }
      }

      if ((codec = rdb_init_collation_mapping(cs)) != nullptr) {
        // The collation allows to store extra information in the unpack_info
        // which can be used to restore the original value from the
        // mem-comparable form.
        m_make_unpack_info_func = codec->m_make_unpack_info_func[idx];
        m_unpack_func = codec->m_unpack_func[idx];
        m_charset_codec = codec;
      } else if (use_unknown_collation) {
        // We have no clue about how this collation produces mem-comparable
        // form. Our way of restoring the original value is to keep a copy of
        // the original value in unpack_info.
        m_unpack_info_stores_value = true;
        m_make_unpack_info_func =
            is_varchar ? &Rdb_key_def::make_unpack_unknown_varchar
                       : &Rdb_key_def::make_unpack_unknown;
        m_unpack_func = is_varchar ? &Rdb_key_def::unpack_unknown_varchar
                                   : &Rdb_key_def::unpack_unknown;
      } else {
        // Same as above: we don't know how to restore the value from its
        // mem-comparable form.
        // Here, we just indicate to the SQL layer we can't do it.
        DBUG_ASSERT(m_unpack_func == nullptr);
        m_unpack_info_stores_value = false;
        res = false; // Indicate that index-only reads are not possible
      }
    }

    // Make an adjustment: unpacking partially covered columns is not
    // possible. field->table is populated when called through
    // Rdb_key_def::setup, but not during ha_rocksdb::index_flags.
    if (field->table) {
      // Get the original Field object and compare lengths. If this key part is
      // a prefix of a column, then we can't do index-only scans.
      if (field->table->field[field->field_index]->field_length != key_length) {
        m_unpack_func = nullptr;
        m_make_unpack_info_func = nullptr;
        m_unpack_info_stores_value = true;
        res = false;
      }
    } else {
      if (field->field_length != key_length) {
        m_unpack_func = nullptr;
        m_make_unpack_info_func = nullptr;
        m_unpack_info_stores_value = true;
        res = false;
      }
    }
  }
  return res;
}

Field *Rdb_field_packing::get_field_in_table(const TABLE *const tbl) const {
  return tbl->key_info[m_keynr].key_part[m_key_part].field;
}

void Rdb_field_packing::fill_hidden_pk_val(uchar **dst,
                                           const longlong &hidden_pk_id) const {
  DBUG_ASSERT(m_max_image_len == 8);

  String to;
  rdb_netstr_append_uint64(&to, hidden_pk_id);
  memcpy(*dst, to.ptr(), m_max_image_len);

  *dst += m_max_image_len;
}

///////////////////////////////////////////////////////////////////////////////////////////
// Rdb_ddl_manager
///////////////////////////////////////////////////////////////////////////////////////////

Rdb_tbl_def::~Rdb_tbl_def() {
  auto ddl_manager = rdb_get_ddl_manager();
  /* Don't free key definitions */
  if (m_key_descr_arr) {
    for (uint i = 0; i < m_key_count; i++) {
      if (ddl_manager && m_key_descr_arr[i]) {
        ddl_manager->erase_index_num(m_key_descr_arr[i]->get_gl_index_id());
      }

      m_key_descr_arr[i] = nullptr;
    }

    delete[] m_key_descr_arr;
    m_key_descr_arr = nullptr;
  }
}

/*
  Put table definition DDL entry. Actual write is done at
  Rdb_dict_manager::commit.

  We write
    dbname.tablename -> version + {key_entry, key_entry, key_entry, ... }

  Where key entries are a tuple of
    ( cf_id, index_nr )
*/

bool Rdb_tbl_def::put_dict(Rdb_dict_manager *const dict,
                           rocksdb::WriteBatch *const batch, uchar *const key,
                           const size_t &keylen) {
  StringBuffer<8 * Rdb_key_def::PACKED_SIZE> indexes;
  indexes.alloc(Rdb_key_def::VERSION_SIZE +
                m_key_count * Rdb_key_def::PACKED_SIZE * 2);
  rdb_netstr_append_uint16(&indexes, Rdb_key_def::DDL_ENTRY_INDEX_VERSION);

  for (uint i = 0; i < m_key_count; i++) {
    const Rdb_key_def &kd = *m_key_descr_arr[i];

    uchar flags =
        (kd.m_is_reverse_cf ? Rdb_key_def::REVERSE_CF_FLAG : 0) |
        (kd.m_is_per_partition_cf ? Rdb_key_def::PER_PARTITION_CF_FLAG : 0);

    const uint cf_id = kd.get_cf()->GetID();
    /*
      If cf_id already exists, cf_flags must be the same.
      To prevent race condition, reading/modifying/committing CF flags
      need to be protected by mutex (dict_manager->lock()).
      When RocksDB supports transaction with pessimistic concurrency
      control, we can switch to use it and removing mutex.
    */
    uint existing_cf_flags;
    const std::string cf_name = kd.get_cf()->GetName();

    if (dict->get_cf_flags(cf_id, &existing_cf_flags)) {
      // For the purposes of comparison we'll clear the partitioning bit. The
      // intent here is to make sure that both partitioned and non-partitioned
      // tables can refer to the same CF.
      existing_cf_flags &= ~Rdb_key_def::CF_FLAGS_TO_IGNORE;
      flags &= ~Rdb_key_def::CF_FLAGS_TO_IGNORE;

      if (existing_cf_flags != flags) {
        my_error(ER_CF_DIFFERENT, MYF(0), cf_name.c_str(), flags,
                 existing_cf_flags);
        return true;
      }
    } else {
      dict->add_cf_flags(batch, cf_id, flags);
    }

    rdb_netstr_append_uint32(&indexes, cf_id);
    rdb_netstr_append_uint32(&indexes, kd.m_index_number);

    struct Rdb_index_info index_info;
    index_info.m_gl_index_id = {cf_id, kd.m_index_number};
    index_info.m_index_dict_version = Rdb_key_def::INDEX_INFO_VERSION_LATEST;
    index_info.m_index_type = kd.m_index_type;
    index_info.m_kv_version = kd.m_kv_format_version;
    index_info.m_index_flags = kd.m_index_flags_bitmap;
    index_info.m_ttl_duration = kd.m_ttl_duration;

    dict->add_or_update_index_cf_mapping(batch, &index_info);
  }

  const rocksdb::Slice skey((char *)key, keylen);
  const rocksdb::Slice svalue(indexes.c_ptr(), indexes.length());

  dict->put_key(batch, skey, svalue);
  return false;
}

// Length that each index flag takes inside the record.
// Each index in the array maps to the enum INDEX_FLAG
static const std::array<int, 1> index_flag_lengths = {
    {ROCKSDB_SIZEOF_TTL_RECORD}};


bool Rdb_key_def::has_index_flag(uint32 index_flags, enum INDEX_FLAG flag) {
  return flag & index_flags;
}

uint32 Rdb_key_def::calculate_index_flag_offset(uint32 index_flags,
                                                enum INDEX_FLAG flag) {

  DBUG_ASSERT(Rdb_key_def::has_index_flag(index_flags, flag));

  uint offset = 0;
  for (size_t bit = 0; bit < sizeof(index_flags) * CHAR_BIT; ++bit) {
    int mask = 1 << bit;

    /* Exit once we've reached the proper flag */
    if (flag & mask) {
      break;
    }

    if (index_flags & mask) {
      offset += index_flag_lengths[bit];
    }
  }

  return offset;
}

void Rdb_tbl_def::check_if_is_mysql_system_table() {
  static const char *const system_dbs[] = {
      "mysql", "performance_schema", "information_schema",
  };

  m_is_mysql_system_table = false;
  for (uint ii = 0; ii < array_elements(system_dbs); ii++) {
    if (strcmp(m_dbname.c_str(), system_dbs[ii]) == 0) {
      m_is_mysql_system_table = true;
      break;
    }
  }
}

void Rdb_tbl_def::set_name(const std::string &name) {
  int err MY_ATTRIBUTE((__unused__));

  m_dbname_tablename = name;
  err = rdb_split_normalized_tablename(name, &m_dbname, &m_tablename,
                                       &m_partition);
  DBUG_ASSERT(err == 0);

  check_if_is_mysql_system_table();
}

/*
  Static function of type my_hash_get_key that gets invoked by
  the m_ddl_hash object of type my_core::HASH.
  It manufactures a key (db+table name in our case) from a record
  (Rdb_tbl_def in our case).
*/
const uchar *
Rdb_ddl_manager::get_hash_key(Rdb_tbl_def *const rec, size_t *const length,
                              my_bool not_used MY_ATTRIBUTE((__unused__))) {
  const std::string &dbname_tablename = rec->full_tablename();
  *length = dbname_tablename.size();
  return reinterpret_cast<const uchar *>(dbname_tablename.c_str());
}

/*
  Static function of type void (*my_hash_free_element_func_t)(void*) that gets
  invoked by the m_ddl_hash object of type my_core::HASH.
  It deletes a record (Rdb_tbl_def in our case).
*/
void Rdb_ddl_manager::free_hash_elem(void *const data) {
  Rdb_tbl_def *elem = reinterpret_cast<Rdb_tbl_def *>(data);
  delete elem;
}

void Rdb_ddl_manager::erase_index_num(const GL_INDEX_ID &gl_index_id) {
  m_index_num_to_keydef.erase(gl_index_id);
}

void Rdb_ddl_manager::add_uncommitted_keydefs(
    const std::unordered_set<std::shared_ptr<Rdb_key_def>> &indexes) {
  mysql_rwlock_wrlock(&m_rwlock);
  for (const auto &index : indexes) {
    m_index_num_to_uncommitted_keydef[index->get_gl_index_id()] = index;
  }
  mysql_rwlock_unlock(&m_rwlock);
}

void Rdb_ddl_manager::remove_uncommitted_keydefs(
    const std::unordered_set<std::shared_ptr<Rdb_key_def>> &indexes) {
  mysql_rwlock_wrlock(&m_rwlock);
  for (const auto &index : indexes) {
    m_index_num_to_uncommitted_keydef.erase(index->get_gl_index_id());
  }
  mysql_rwlock_unlock(&m_rwlock);
}

namespace // anonymous namespace = not visible outside this source file
{
struct Rdb_validate_tbls : public Rdb_tables_scanner {
  using tbl_info_t = std::pair<std::string, bool>;
  using tbl_list_t = std::map<std::string, std::set<tbl_info_t>>;

  tbl_list_t m_list;

  int add_table(Rdb_tbl_def *tdef) override;

  bool compare_to_actual_tables(const std::string &datadir, bool *has_errors);

  bool scan_for_frms(const std::string &datadir, const std::string &dbname,
                     bool *has_errors);

  bool check_frm_file(const std::string &fullpath, const std::string &dbname,
                      const std::string &tablename, bool *has_errors);
};
} // anonymous namespace

/*
  Get a list of tables that we expect to have .frm files for.  This will use the
  information just read from the RocksDB data dictionary.
*/
int Rdb_validate_tbls::add_table(Rdb_tbl_def *tdef) {
  DBUG_ASSERT(tdef != nullptr);

  /* Add the database/table into the list */
  bool is_partition = tdef->base_partition().size() != 0;
  m_list[tdef->base_dbname()].insert(
      tbl_info_t(tdef->base_tablename(), is_partition));

  return HA_EXIT_SUCCESS;
}

/*
  Access the .frm file for this dbname/tablename and see if it is a RocksDB
  table (or partition table).
*/
bool Rdb_validate_tbls::check_frm_file(const std::string &fullpath,
                                       const std::string &dbname,
                                       const std::string &tablename,
                                       bool *has_errors) {
  /* Check this .frm file to see what engine it uses */
  String fullfilename(fullpath.c_str(), &my_charset_bin);
  fullfilename.append(FN_DIRSEP);
  fullfilename.append(tablename.c_str());
  fullfilename.append(".frm");

  /*
    This function will return the legacy_db_type of the table.  Currently
    it does not reference the first parameter (THD* thd), but if it ever
    did in the future we would need to make a version that does it without
    the connection handle as we don't have one here.
  */
  char eng_type_buf[NAME_CHAR_LEN+1];
  LEX_CSTRING eng_type_str = {eng_type_buf, 0}; 
  bool is_sequence;
  enum Table_type type = dd_frm_type(nullptr, fullfilename.c_ptr(), &eng_type_str, &is_sequence);
  if (type == TABLE_TYPE_UNKNOWN) {
    sql_print_warning("RocksDB: Failed to open/read .from file: %s",
                      fullfilename.ptr());
    return false;
  }

  if (type == TABLE_TYPE_NORMAL) {
    /* For a RocksDB table do we have a reference in the data dictionary? */
    if (!strncmp(eng_type_str.str, "ROCKSDB", eng_type_str.length)) {
      /*
        Attempt to remove the table entry from the list of tables.  If this
        fails then we know we had a .frm file that wasn't registered in RocksDB.
      */
      tbl_info_t element(tablename, false);
      if (m_list.count(dbname) == 0 || m_list[dbname].erase(element) == 0) {
        sql_print_warning("RocksDB: Schema mismatch - "
                          "A .frm file exists for table %s.%s, "
                          "but that table is not registered in RocksDB",
                          dbname.c_str(), tablename.c_str());
        *has_errors = true;
      }
    } else if (!strncmp(eng_type_str.str, "partition", eng_type_str.length)) {
      /*
        For partition tables, see if it is in the m_list as a partition,
        but don't generate an error if it isn't there - we don't know that the
        .frm is for RocksDB.
      */
      if (m_list.count(dbname) > 0) {
        m_list[dbname].erase(tbl_info_t(tablename, true));
      }
    }
  }

  return true;
}

/* Scan the database subdirectory for .frm files */
bool Rdb_validate_tbls::scan_for_frms(const std::string &datadir,
                                      const std::string &dbname,
                                      bool *has_errors) {
  bool result = true;
  std::string fullpath = datadir + dbname;
  struct st_my_dir *dir_info = my_dir(fullpath.c_str(), MYF(MY_DONT_SORT));

  /* Access the directory */
  if (dir_info == nullptr) {
    sql_print_warning("RocksDB: Could not open database directory: %s",
                      fullpath.c_str());
    return false;
  }

  /* Scan through the files in the directory */
  struct fileinfo *file_info = dir_info->dir_entry;
  for (uint ii = 0; ii < dir_info->number_of_files; ii++, file_info++) {
    /* Find .frm files that are not temp files (those that start with '#') */
    const char *ext = strrchr(file_info->name, '.');
    if (ext != nullptr && !is_prefix(file_info->name, tmp_file_prefix) &&
        strcmp(ext, ".frm") == 0) {
      std::string tablename =
          std::string(file_info->name, ext - file_info->name);

      /* Check to see if the .frm file is from RocksDB */
      if (!check_frm_file(fullpath, dbname, tablename, has_errors)) {
        result = false;
        break;
      }
    }
  }

  /* Remove any databases who have no more tables listed */
  if (m_list.count(dbname) == 1 && m_list[dbname].size() == 0) {
    m_list.erase(dbname);
  }

  /* Release the directory entry */
  my_dirend(dir_info);

  return result;
}

/*
  Scan the datadir for all databases (subdirectories) and get a list of .frm
  files they contain
*/
bool Rdb_validate_tbls::compare_to_actual_tables(const std::string &datadir,
                                                 bool *has_errors) {
  bool result = true;
  struct st_my_dir *dir_info;
  struct fileinfo *file_info;

  dir_info = my_dir(datadir.c_str(), MYF(MY_DONT_SORT | MY_WANT_STAT));
  if (dir_info == nullptr) {
    sql_print_warning("RocksDB: could not open datadir: %s", datadir.c_str());
    return false;
  }

  file_info = dir_info->dir_entry;
  for (uint ii = 0; ii < dir_info->number_of_files; ii++, file_info++) {
    /* Ignore files/dirs starting with '.' */
    if (file_info->name[0] == '.')
      continue;

    /* Ignore all non-directory files */
    if (!MY_S_ISDIR(file_info->mystat->st_mode))
      continue;

    /* Scan all the .frm files in the directory */
    if (!scan_for_frms(datadir, file_info->name, has_errors)) {
      result = false;
      break;
    }
  }

  /* Release the directory info */
  my_dirend(dir_info);

  return result;
}

/*
  Validate that all the tables in the RocksDB database dictionary match the .frm
  files in the datadir
*/
bool Rdb_ddl_manager::validate_schemas(void) {
  bool has_errors = false;
  const std::string datadir = std::string(mysql_real_data_home);
  Rdb_validate_tbls table_list;

  /* Get the list of tables from the database dictionary */
  if (scan_for_tables(&table_list) != 0) {
    return false;
  }

  /* Compare that to the list of actual .frm files */
  if (!table_list.compare_to_actual_tables(datadir, &has_errors)) {
    return false;
  }

  /*
    Any tables left in the tables list are ones that are registered in RocksDB
    but don't have .frm files.
  */
  for (const auto &db : table_list.m_list) {
    for (const auto &table : db.second) {
      sql_print_warning("RocksDB: Schema mismatch - "
                        "Table %s.%s is registered in RocksDB "
                        "but does not have a .frm file",
                        db.first.c_str(), table.first.c_str());
      has_errors = true;
    }
  }

  return !has_errors;
}

bool Rdb_ddl_manager::init(Rdb_dict_manager *const dict_arg,
                           Rdb_cf_manager *const cf_manager,
                           const uint32_t &validate_tables) {
  const ulong TABLE_HASH_SIZE = 32;
  m_dict = dict_arg;
  mysql_rwlock_init(0, &m_rwlock);
  (void)my_hash_init(&m_ddl_hash,
                     /*system_charset_info*/ &my_charset_bin, TABLE_HASH_SIZE,
                     0, 0, (my_hash_get_key)Rdb_ddl_manager::get_hash_key,
                     Rdb_ddl_manager::free_hash_elem, 0);

  /* Read the data dictionary and populate the hash */
  uchar ddl_entry[Rdb_key_def::INDEX_NUMBER_SIZE];
  rdb_netbuf_store_index(ddl_entry, Rdb_key_def::DDL_ENTRY_INDEX_START_NUMBER);
  const rocksdb::Slice ddl_entry_slice((char *)ddl_entry,
                                       Rdb_key_def::INDEX_NUMBER_SIZE);

  /* Reading data dictionary should always skip bloom filter */
  rocksdb::Iterator *it = m_dict->new_iterator();
  int i = 0;

  uint max_index_id_in_dict = 0;
  m_dict->get_max_index_id(&max_index_id_in_dict);

  for (it->Seek(ddl_entry_slice); it->Valid(); it->Next()) {
    const uchar *ptr;
    const uchar *ptr_end;
    const rocksdb::Slice key = it->key();
    const rocksdb::Slice val = it->value();

    if (key.size() >= Rdb_key_def::INDEX_NUMBER_SIZE &&
        memcmp(key.data(), ddl_entry, Rdb_key_def::INDEX_NUMBER_SIZE))
      break;

    if (key.size() <= Rdb_key_def::INDEX_NUMBER_SIZE) {
      sql_print_error("RocksDB: Table_store: key has length %d (corruption?)",
                      (int)key.size());
      return true;
    }

    Rdb_tbl_def *const tdef =
        new Rdb_tbl_def(key, Rdb_key_def::INDEX_NUMBER_SIZE);

    // Now, read the DDLs.
    const int real_val_size = val.size() - Rdb_key_def::VERSION_SIZE;
    if (real_val_size % Rdb_key_def::PACKED_SIZE * 2 > 0) {
      sql_print_error("RocksDB: Table_store: invalid keylist for table %s",
                      tdef->full_tablename().c_str());
      return true;
    }
    tdef->m_key_count = real_val_size / (Rdb_key_def::PACKED_SIZE * 2);
    tdef->m_key_descr_arr = new std::shared_ptr<Rdb_key_def>[tdef->m_key_count];

    ptr = reinterpret_cast<const uchar *>(val.data());
    const int version = rdb_netbuf_read_uint16(&ptr);
    if (version != Rdb_key_def::DDL_ENTRY_INDEX_VERSION) {
      sql_print_error("RocksDB: DDL ENTRY Version was not expected."
                      "Expected: %d, Actual: %d",
                      Rdb_key_def::DDL_ENTRY_INDEX_VERSION, version);
      return true;
    }
    ptr_end = ptr + real_val_size;
    for (uint keyno = 0; ptr < ptr_end; keyno++) {
      GL_INDEX_ID gl_index_id;
      rdb_netbuf_read_gl_index(&ptr, &gl_index_id);
      uint flags = 0;
      struct Rdb_index_info index_info;
      if (!m_dict->get_index_info(gl_index_id, &index_info)) {
        sql_print_error("RocksDB: Could not get index information "
                        "for Index Number (%u,%u), table %s",
                        gl_index_id.cf_id, gl_index_id.index_id,
                        tdef->full_tablename().c_str());
        return true;
      }
      if (max_index_id_in_dict < gl_index_id.index_id) {
        sql_print_error("RocksDB: Found max index id %u from data dictionary "
                        "but also found larger index id %u from dictionary. "
                        "This should never happen and possibly a bug.",
                        max_index_id_in_dict, gl_index_id.index_id);
        return true;
      }
      if (!m_dict->get_cf_flags(gl_index_id.cf_id, &flags)) {
        sql_print_error("RocksDB: Could not get Column Family Flags "
                        "for CF Number %d, table %s",
                        gl_index_id.cf_id, tdef->full_tablename().c_str());
        return true;
      }

      if ((flags & Rdb_key_def::AUTO_CF_FLAG) != 0) {
        // The per-index cf option is deprecated.  Make sure we don't have the
        // flag set in any existing database.   NO_LINT_DEBUG
        sql_print_error("RocksDB: The defunct AUTO_CF_FLAG is enabled for CF "
                        "number %d, table %s",
                        gl_index_id.cf_id, tdef->full_tablename().c_str());
      }

      rocksdb::ColumnFamilyHandle *const cfh =
          cf_manager->get_cf(gl_index_id.cf_id);
      DBUG_ASSERT(cfh != nullptr);

      uint32 ttl_rec_offset =
          Rdb_key_def::has_index_flag(index_info.m_index_flags,
                                      Rdb_key_def::TTL_FLAG)
              ? Rdb_key_def::calculate_index_flag_offset(
                    index_info.m_index_flags, Rdb_key_def::TTL_FLAG)
              : UINT_MAX;

      /*
        We can't fully initialize Rdb_key_def object here, because full
        initialization requires that there is an open TABLE* where we could
        look at Field* objects and set max_length and other attributes
      */
      tdef->m_key_descr_arr[keyno] = std::make_shared<Rdb_key_def>(
          gl_index_id.index_id, keyno, cfh, index_info.m_index_dict_version,
          index_info.m_index_type, index_info.m_kv_version,
          flags & Rdb_key_def::REVERSE_CF_FLAG,
          flags & Rdb_key_def::PER_PARTITION_CF_FLAG, "",
          m_dict->get_stats(gl_index_id), index_info.m_index_flags,
          ttl_rec_offset, index_info.m_ttl_duration);
    }
    put(tdef);
    i++;
  }

  /*
    If validate_tables is greater than 0 run the validation.  Only fail the
    initialzation if the setting is 1.  If the setting is 2 we continue.
  */
  if (validate_tables > 0 && !validate_schemas()) {
    if (validate_tables == 1) {
      sql_print_error("RocksDB: Problems validating data dictionary "
                      "against .frm files, exiting");
      return true;
    }
  }

  // index ids used by applications should not conflict with
  // data dictionary index ids
  if (max_index_id_in_dict < Rdb_key_def::END_DICT_INDEX_ID) {
    max_index_id_in_dict = Rdb_key_def::END_DICT_INDEX_ID;
  }

  m_sequence.init(max_index_id_in_dict + 1);

  if (!it->status().ok()) {
    rdb_log_status_error(it->status(), "Table_store load error");
    return true;
  }
  delete it;
  sql_print_information("RocksDB: Table_store: loaded DDL data for %d tables",
                        i);
  return false;
}

Rdb_tbl_def *Rdb_ddl_manager::find(const std::string &table_name,
                                   const bool &lock) {
  if (lock) {
    mysql_rwlock_rdlock(&m_rwlock);
  }

  Rdb_tbl_def *const rec = reinterpret_cast<Rdb_tbl_def *>(my_hash_search(
      &m_ddl_hash, reinterpret_cast<const uchar *>(table_name.c_str()),
      table_name.size()));

  if (lock) {
    mysql_rwlock_unlock(&m_rwlock);
  }

  return rec;
}

// this is a safe version of the find() function below.  It acquires a read
// lock on m_rwlock to make sure the Rdb_key_def is not discarded while we
// are finding it.  Copying it into 'ret' increments the count making sure
// that the object will not be discarded until we are finished with it.
std::shared_ptr<const Rdb_key_def>
Rdb_ddl_manager::safe_find(GL_INDEX_ID gl_index_id) {
  std::shared_ptr<const Rdb_key_def> ret(nullptr);

  mysql_rwlock_rdlock(&m_rwlock);

  auto it = m_index_num_to_keydef.find(gl_index_id);
  if (it != m_index_num_to_keydef.end()) {
    const auto table_def = find(it->second.first, false);
    if (table_def && it->second.second < table_def->m_key_count) {
      const auto &kd = table_def->m_key_descr_arr[it->second.second];
      if (kd->max_storage_fmt_length() != 0) {
        ret = kd;
      }
    }
  } else {
    auto it = m_index_num_to_uncommitted_keydef.find(gl_index_id);
    if (it != m_index_num_to_uncommitted_keydef.end()) {
      const auto &kd = it->second;
      if (kd->max_storage_fmt_length() != 0) {
        ret = kd;
      }
    }
  }

  mysql_rwlock_unlock(&m_rwlock);

  return ret;
}

// this method assumes at least read-only lock on m_rwlock
const std::shared_ptr<Rdb_key_def> &
Rdb_ddl_manager::find(GL_INDEX_ID gl_index_id) {
  auto it = m_index_num_to_keydef.find(gl_index_id);
  if (it != m_index_num_to_keydef.end()) {
    auto table_def = find(it->second.first, false);
    if (table_def) {
      if (it->second.second < table_def->m_key_count) {
        return table_def->m_key_descr_arr[it->second.second];
      }
    }
  } else {
    auto it = m_index_num_to_uncommitted_keydef.find(gl_index_id);
    if (it != m_index_num_to_uncommitted_keydef.end()) {
      return it->second;
    }
  }

  static std::shared_ptr<Rdb_key_def> empty = nullptr;

  return empty;
}

void Rdb_ddl_manager::set_stats(
    const std::unordered_map<GL_INDEX_ID, Rdb_index_stats> &stats) {
  mysql_rwlock_wrlock(&m_rwlock);
  for (auto src : stats) {
    const auto &keydef = find(src.second.m_gl_index_id);
    if (keydef) {
      keydef->m_stats = src.second;
      m_stats2store[keydef->m_stats.m_gl_index_id] = keydef->m_stats;
    }
  }
  mysql_rwlock_unlock(&m_rwlock);
}

void Rdb_ddl_manager::adjust_stats(
    const std::vector<Rdb_index_stats> &new_data,
    const std::vector<Rdb_index_stats> &deleted_data) {
  mysql_rwlock_wrlock(&m_rwlock);
  int i = 0;
  for (const auto &data : {new_data, deleted_data}) {
    for (const auto &src : data) {
      const auto &keydef = find(src.m_gl_index_id);
      if (keydef) {
        keydef->m_stats.m_distinct_keys_per_prefix.resize(
            keydef->get_key_parts());
        keydef->m_stats.merge(src, i == 0, keydef->max_storage_fmt_length());
        m_stats2store[keydef->m_stats.m_gl_index_id] = keydef->m_stats;
      }
    }
    i++;
  }
  const bool should_save_stats = !m_stats2store.empty();
  mysql_rwlock_unlock(&m_rwlock);
  if (should_save_stats) {
    // Queue an async persist_stats(false) call to the background thread.
    rdb_queue_save_stats_request();
  }
}

void Rdb_ddl_manager::persist_stats(const bool &sync) {
  mysql_rwlock_wrlock(&m_rwlock);
  const auto local_stats2store = std::move(m_stats2store);
  m_stats2store.clear();
  mysql_rwlock_unlock(&m_rwlock);

  // Persist stats
  const std::unique_ptr<rocksdb::WriteBatch> wb = m_dict->begin();
  std::vector<Rdb_index_stats> stats;
  std::transform(local_stats2store.begin(), local_stats2store.end(),
                 std::back_inserter(stats),
                 [](const std::pair<GL_INDEX_ID, Rdb_index_stats> &s) {
                   return s.second;
                 });
  m_dict->add_stats(wb.get(), stats);
  m_dict->commit(wb.get(), sync);
}

/*
  Put table definition of `tbl` into the mapping, and also write it to the
  on-disk data dictionary.
*/

int Rdb_ddl_manager::put_and_write(Rdb_tbl_def *const tbl,
                                   rocksdb::WriteBatch *const batch) {
  uchar buf[FN_LEN * 2 + Rdb_key_def::INDEX_NUMBER_SIZE];
  uint pos = 0;

  rdb_netbuf_store_index(buf, Rdb_key_def::DDL_ENTRY_INDEX_START_NUMBER);
  pos += Rdb_key_def::INDEX_NUMBER_SIZE;

  const std::string &dbname_tablename = tbl->full_tablename();
  memcpy(buf + pos, dbname_tablename.c_str(), dbname_tablename.size());
  pos += dbname_tablename.size();

  int res;
  if ((res = tbl->put_dict(m_dict, batch, buf, pos))) {
    return res;
  }
  if ((res = put(tbl))) {
    return res;
  }
  return HA_EXIT_SUCCESS;
}

/* Return 0 - ok, other value - error */
/* TODO:
  This function modifies m_ddl_hash and m_index_num_to_keydef.
  However, these changes need to be reversed if dict_manager.commit fails
  See the discussion here: https://reviews.facebook.net/D35925#inline-259167
  Tracked by https://github.com/facebook/mysql-5.6/issues/33
*/
int Rdb_ddl_manager::put(Rdb_tbl_def *const tbl, const bool &lock) {
  Rdb_tbl_def *rec;
  my_bool result;
  const std::string &dbname_tablename = tbl->full_tablename();

  if (lock)
    mysql_rwlock_wrlock(&m_rwlock);

  // We have to do this find because 'tbl' is not yet in the list.  We need
  // to find the one we are replacing ('rec')
  rec = find(dbname_tablename, false);
  if (rec) {
    // this will free the old record.
    my_hash_delete(&m_ddl_hash, reinterpret_cast<uchar *>(rec));
  }
  result = my_hash_insert(&m_ddl_hash, reinterpret_cast<uchar *>(tbl));

  for (uint keyno = 0; keyno < tbl->m_key_count; keyno++) {
    m_index_num_to_keydef[tbl->m_key_descr_arr[keyno]->get_gl_index_id()] =
        std::make_pair(dbname_tablename, keyno);
  }

  if (lock)
    mysql_rwlock_unlock(&m_rwlock);
  return result;
}

void Rdb_ddl_manager::remove(Rdb_tbl_def *const tbl,
                             rocksdb::WriteBatch *const batch,
                             const bool &lock) {
  if (lock)
    mysql_rwlock_wrlock(&m_rwlock);

  uchar buf[FN_LEN * 2 + Rdb_key_def::INDEX_NUMBER_SIZE];
  uint pos = 0;

  rdb_netbuf_store_index(buf, Rdb_key_def::DDL_ENTRY_INDEX_START_NUMBER);
  pos += Rdb_key_def::INDEX_NUMBER_SIZE;

  const std::string &dbname_tablename = tbl->full_tablename();
  memcpy(buf + pos, dbname_tablename.c_str(), dbname_tablename.size());
  pos += dbname_tablename.size();

  const rocksdb::Slice tkey((char *)buf, pos);
  m_dict->delete_key(batch, tkey);

  /* The following will also delete the object: */
  my_hash_delete(&m_ddl_hash, reinterpret_cast<uchar *>(tbl));

  if (lock)
    mysql_rwlock_unlock(&m_rwlock);
}

bool Rdb_ddl_manager::rename(const std::string &from, const std::string &to,
                             rocksdb::WriteBatch *const batch) {
  Rdb_tbl_def *rec;
  Rdb_tbl_def *new_rec;
  bool res = true;
  uchar new_buf[FN_LEN * 2 + Rdb_key_def::INDEX_NUMBER_SIZE];
  uint new_pos = 0;

  mysql_rwlock_wrlock(&m_rwlock);
  if (!(rec = find(from, false))) {
    mysql_rwlock_unlock(&m_rwlock);
    return true;
  }

  new_rec = new Rdb_tbl_def(to);

  new_rec->m_key_count = rec->m_key_count;
  new_rec->m_auto_incr_val =
      rec->m_auto_incr_val.load(std::memory_order_relaxed);
  new_rec->m_key_descr_arr = rec->m_key_descr_arr;
  // so that it's not free'd when deleting the old rec
  rec->m_key_descr_arr = nullptr;

  // Create a new key
  rdb_netbuf_store_index(new_buf, Rdb_key_def::DDL_ENTRY_INDEX_START_NUMBER);
  new_pos += Rdb_key_def::INDEX_NUMBER_SIZE;

  const std::string &dbname_tablename = new_rec->full_tablename();
  memcpy(new_buf + new_pos, dbname_tablename.c_str(), dbname_tablename.size());
  new_pos += dbname_tablename.size();

  // Create a key to add
  if (!new_rec->put_dict(m_dict, batch, new_buf, new_pos)) {
    remove(rec, batch, false);
    put(new_rec, false);
    res = false; // ok
  }

  mysql_rwlock_unlock(&m_rwlock);
  return res;
}

void Rdb_ddl_manager::cleanup() {
  my_hash_free(&m_ddl_hash);
  mysql_rwlock_destroy(&m_rwlock);
  m_sequence.cleanup();
}

int Rdb_ddl_manager::scan_for_tables(Rdb_tables_scanner *const tables_scanner) {
  int i, ret;
  Rdb_tbl_def *rec;

  DBUG_ASSERT(tables_scanner != nullptr);

  mysql_rwlock_rdlock(&m_rwlock);

  ret = 0;
  i = 0;

  while ((
      rec = reinterpret_cast<Rdb_tbl_def *>(my_hash_element(&m_ddl_hash, i)))) {
    ret = tables_scanner->add_table(rec);
    if (ret)
      break;
    i++;
  }

  mysql_rwlock_unlock(&m_rwlock);
  return ret;
}

/*
  Rdb_binlog_manager class implementation
*/

bool Rdb_binlog_manager::init(Rdb_dict_manager *const dict_arg) {
  DBUG_ASSERT(dict_arg != nullptr);
  m_dict = dict_arg;

  rdb_netbuf_store_index(m_key_buf, Rdb_key_def::BINLOG_INFO_INDEX_NUMBER);
  m_key_slice = rocksdb::Slice(reinterpret_cast<char *>(m_key_buf),
                               Rdb_key_def::INDEX_NUMBER_SIZE);
  return false;
}

void Rdb_binlog_manager::cleanup() {}

/**
  Set binlog name, pos and optionally gtid into WriteBatch.
  This function should be called as part of transaction commit,
  since binlog info is set only at transaction commit.
  Actual write into RocksDB is not done here, so checking if
  write succeeded or not is not possible here.
  @param binlog_name   Binlog name
  @param binlog_pos    Binlog pos
  @param binlog_gtid   Binlog max GTID
  @param batch         WriteBatch
*/
void Rdb_binlog_manager::update(const char *const binlog_name,
                                const my_off_t binlog_pos,
                                const char *const binlog_max_gtid,
                                rocksdb::WriteBatchBase *const batch) {
  if (binlog_name && binlog_pos) {
    // max binlog length (512) + binlog pos (4) + binlog gtid (57) < 1024
    const size_t RDB_MAX_BINLOG_INFO_LEN = 1024;
    uchar value_buf[RDB_MAX_BINLOG_INFO_LEN];
    m_dict->put_key(
        batch, m_key_slice,
        pack_value(value_buf, binlog_name, binlog_pos, binlog_max_gtid));
  }
}

/**
  Read binlog committed entry stored in RocksDB, then unpack
  @param[OUT] binlog_name  Binlog name
  @param[OUT] binlog_pos   Binlog pos
  @param[OUT] binlog_gtid  Binlog GTID
  @return
    true is binlog info was found (valid behavior)
    false otherwise
*/
bool Rdb_binlog_manager::read(char *const binlog_name,
                              my_off_t *const binlog_pos,
                              char *const binlog_gtid) const {
  bool ret = false;
  if (binlog_name) {
    std::string value;
    rocksdb::Status status = m_dict->get_value(m_key_slice, &value);
    if (status.ok()) {
      if (!unpack_value((const uchar *)value.c_str(), binlog_name, binlog_pos,
                        binlog_gtid))
        ret = true;
    }
  }
  return ret;
}

/**
  Pack binlog_name, binlog_pos, binlog_gtid into preallocated
  buffer, then converting and returning a RocksDB Slice
  @param buf           Preallocated buffer to set binlog info.
  @param binlog_name   Binlog name
  @param binlog_pos    Binlog pos
  @param binlog_gtid   Binlog GTID
  @return              rocksdb::Slice converted from buf and its length
*/
rocksdb::Slice
Rdb_binlog_manager::pack_value(uchar *const buf, const char *const binlog_name,
                               const my_off_t &binlog_pos,
                               const char *const binlog_gtid) const {
  uint pack_len = 0;

  // store version
  rdb_netbuf_store_uint16(buf, Rdb_key_def::BINLOG_INFO_INDEX_NUMBER_VERSION);
  pack_len += Rdb_key_def::VERSION_SIZE;

  // store binlog file name length
  DBUG_ASSERT(strlen(binlog_name) <= FN_REFLEN);
  const uint16_t binlog_name_len = (uint16_t)strlen(binlog_name);
  rdb_netbuf_store_uint16(buf + pack_len, binlog_name_len);
  pack_len += sizeof(uint16);

  // store binlog file name
  memcpy(buf + pack_len, binlog_name, binlog_name_len);
  pack_len += binlog_name_len;

  // store binlog pos
  rdb_netbuf_store_uint32(buf + pack_len, binlog_pos);
  pack_len += sizeof(uint32);

  // store binlog gtid length.
  // If gtid was not set, store 0 instead
  const uint16_t binlog_gtid_len = binlog_gtid ? (uint16_t)strlen(binlog_gtid) : 0;
  rdb_netbuf_store_uint16(buf + pack_len, binlog_gtid_len);
  pack_len += sizeof(uint16);

  if (binlog_gtid_len > 0) {
    // store binlog gtid
    memcpy(buf + pack_len, binlog_gtid, binlog_gtid_len);
    pack_len += binlog_gtid_len;
  }

  return rocksdb::Slice((char *)buf, pack_len);
}

/**
  Unpack value then split into binlog_name, binlog_pos (and binlog_gtid)
  @param[IN]  value        Binlog state info fetched from RocksDB
  @param[OUT] binlog_name  Binlog name
  @param[OUT] binlog_pos   Binlog pos
  @param[OUT] binlog_gtid  Binlog GTID
  @return     true on error
*/
bool Rdb_binlog_manager::unpack_value(const uchar *const value,
                                      char *const binlog_name,
                                      my_off_t *const binlog_pos,
                                      char *const binlog_gtid) const {
  uint pack_len = 0;

  DBUG_ASSERT(binlog_pos != nullptr);

  // read version
  const uint16_t version = rdb_netbuf_to_uint16(value);
  pack_len += Rdb_key_def::VERSION_SIZE;
  if (version != Rdb_key_def::BINLOG_INFO_INDEX_NUMBER_VERSION)
    return true;

  // read binlog file name length
  const uint16_t binlog_name_len = rdb_netbuf_to_uint16(value + pack_len);
  pack_len += sizeof(uint16);
  if (binlog_name_len) {
    // read and set binlog name
    memcpy(binlog_name, value + pack_len, binlog_name_len);
    binlog_name[binlog_name_len] = '\0';
    pack_len += binlog_name_len;

    // read and set binlog pos
    *binlog_pos = rdb_netbuf_to_uint32(value + pack_len);
    pack_len += sizeof(uint32);

    // read gtid length
    const uint16_t binlog_gtid_len = rdb_netbuf_to_uint16(value + pack_len);
    pack_len += sizeof(uint16);
    if (binlog_gtid && binlog_gtid_len > 0) {
      // read and set gtid
      memcpy(binlog_gtid, value + pack_len, binlog_gtid_len);
      binlog_gtid[binlog_gtid_len] = '\0';
      pack_len += binlog_gtid_len;
    }
  }
  return false;
}

/**
  Inserts a row into mysql.slave_gtid_info table. Doing this inside
  storage engine is more efficient than inserting/updating through MySQL.

  @param[IN] id Primary key of the table.
  @param[IN] db Database name. This is column 2 of the table.
  @param[IN] gtid Gtid in human readable form. This is column 3 of the table.
  @param[IN] write_batch Handle to storage engine writer.
*/
void Rdb_binlog_manager::update_slave_gtid_info(
    const uint &id, const char *const db, const char *const gtid,
    rocksdb::WriteBatchBase *const write_batch) {
  if (id && db && gtid) {
    // Make sure that if the slave_gtid_info table exists we have a
    // pointer to it via m_slave_gtid_info_tbl.
    if (!m_slave_gtid_info_tbl.load()) {
      m_slave_gtid_info_tbl.store(
          rdb_get_ddl_manager()->find("mysql.slave_gtid_info"));
    }
    if (!m_slave_gtid_info_tbl.load()) {
      // slave_gtid_info table is not present. Simply return.
      return;
    }
    DBUG_ASSERT(m_slave_gtid_info_tbl.load()->m_key_count == 1);

    const std::shared_ptr<const Rdb_key_def> &kd =
        m_slave_gtid_info_tbl.load()->m_key_descr_arr[0];
    String value;

    // Build key
    uchar key_buf[Rdb_key_def::INDEX_NUMBER_SIZE + 4] = {0};
    uchar *buf = key_buf;
    rdb_netbuf_store_index(buf, kd->get_index_number());
    buf += Rdb_key_def::INDEX_NUMBER_SIZE;
    rdb_netbuf_store_uint32(buf, id);
    buf += 4;
    const rocksdb::Slice key_slice =
        rocksdb::Slice((const char *)key_buf, buf - key_buf);

    // Build value
    uchar value_buf[128] = {0};
    DBUG_ASSERT(gtid);
    const uint db_len = strlen(db);
    const uint gtid_len = strlen(gtid);
    buf = value_buf;
    // 1 byte used for flags. Empty here.
    buf++;

    // Write column 1.
    DBUG_ASSERT(strlen(db) <= 64);
    rdb_netbuf_store_byte(buf, db_len);
    buf++;
    memcpy(buf, db, db_len);
    buf += db_len;

    // Write column 2.
    DBUG_ASSERT(gtid_len <= 56);
    rdb_netbuf_store_byte(buf, gtid_len);
    buf++;
    memcpy(buf, gtid, gtid_len);
    buf += gtid_len;
    const rocksdb::Slice value_slice =
        rocksdb::Slice((const char *)value_buf, buf - value_buf);

    write_batch->Put(kd->get_cf(), key_slice, value_slice);
  }
}

bool Rdb_dict_manager::init(rocksdb::DB *const rdb_dict,
                            Rdb_cf_manager *const cf_manager) {
  DBUG_ASSERT(rdb_dict != nullptr);
  DBUG_ASSERT(cf_manager != nullptr);

  mysql_mutex_init(0, &m_mutex, MY_MUTEX_INIT_FAST);

  m_db = rdb_dict;

  m_system_cfh = cf_manager->get_or_create_cf(m_db, DEFAULT_SYSTEM_CF_NAME);
  rocksdb::ColumnFamilyHandle *default_cfh =
      cf_manager->get_cf(DEFAULT_CF_NAME);

  // System CF and default CF should be initialized
  if (m_system_cfh == nullptr || default_cfh == nullptr) {
    return HA_EXIT_FAILURE;
  }

  rdb_netbuf_store_index(m_key_buf_max_index_id, Rdb_key_def::MAX_INDEX_ID);

  m_key_slice_max_index_id =
      rocksdb::Slice(reinterpret_cast<char *>(m_key_buf_max_index_id),
                     Rdb_key_def::INDEX_NUMBER_SIZE);

  resume_drop_indexes();
  rollback_ongoing_index_creation();

  // Initialize system CF and default CF flags
  const std::unique_ptr<rocksdb::WriteBatch> wb = begin();
  rocksdb::WriteBatch *const batch = wb.get();

  add_cf_flags(batch, m_system_cfh->GetID(), 0);
  add_cf_flags(batch, default_cfh->GetID(), 0);
  commit(batch);

  return HA_EXIT_SUCCESS;
}

std::unique_ptr<rocksdb::WriteBatch> Rdb_dict_manager::begin() const {
  return std::unique_ptr<rocksdb::WriteBatch>(new rocksdb::WriteBatch);
}

void Rdb_dict_manager::put_key(rocksdb::WriteBatchBase *const batch,
                               const rocksdb::Slice &key,
                               const rocksdb::Slice &value) const {
  batch->Put(m_system_cfh, key, value);
}

rocksdb::Status Rdb_dict_manager::get_value(const rocksdb::Slice &key,
                                            std::string *const value) const {
  rocksdb::ReadOptions options;
  options.total_order_seek = true;
  return m_db->Get(options, m_system_cfh, key, value);
}

void Rdb_dict_manager::delete_key(rocksdb::WriteBatchBase *batch,
                                  const rocksdb::Slice &key) const {
  batch->Delete(m_system_cfh, key);
}

rocksdb::Iterator *Rdb_dict_manager::new_iterator() const {
  /* Reading data dictionary should always skip bloom filter */
  rocksdb::ReadOptions read_options;
  read_options.total_order_seek = true;
  return m_db->NewIterator(read_options, m_system_cfh);
}

int Rdb_dict_manager::commit(rocksdb::WriteBatch *const batch,
                             const bool &sync) const {
  if (!batch)
    return HA_ERR_ROCKSDB_COMMIT_FAILED;
  int res = HA_EXIT_SUCCESS;
  rocksdb::WriteOptions options;
  options.sync = sync;
  rocksdb::Status s = m_db->Write(options, batch);
  res = !s.ok(); // we return true when something failed
  if (res) {
    rdb_handle_io_error(s, RDB_IO_ERROR_DICT_COMMIT);
  }
  batch->Clear();
  return res;
}

void Rdb_dict_manager::dump_index_id(uchar *const netbuf,
                                     Rdb_key_def::DATA_DICT_TYPE dict_type,
                                     const GL_INDEX_ID &gl_index_id) {
  rdb_netbuf_store_uint32(netbuf, dict_type);
  rdb_netbuf_store_uint32(netbuf + Rdb_key_def::INDEX_NUMBER_SIZE,
                          gl_index_id.cf_id);
  rdb_netbuf_store_uint32(netbuf + 2 * Rdb_key_def::INDEX_NUMBER_SIZE,
                          gl_index_id.index_id);
}

void Rdb_dict_manager::delete_with_prefix(
    rocksdb::WriteBatch *const batch, Rdb_key_def::DATA_DICT_TYPE dict_type,
    const GL_INDEX_ID &gl_index_id) const {
  uchar key_buf[Rdb_key_def::INDEX_NUMBER_SIZE * 3] = {0};
  dump_index_id(key_buf, dict_type, gl_index_id);
  rocksdb::Slice key = rocksdb::Slice((char *)key_buf, sizeof(key_buf));

  delete_key(batch, key);
}

void Rdb_dict_manager::add_or_update_index_cf_mapping(
    rocksdb::WriteBatch *batch, struct Rdb_index_info *const index_info) const {
  uchar key_buf[Rdb_key_def::INDEX_NUMBER_SIZE * 3] = {0};
  uchar value_buf[256] = {0};
  dump_index_id(key_buf, Rdb_key_def::INDEX_INFO, index_info->m_gl_index_id);
  const rocksdb::Slice key = rocksdb::Slice((char *)key_buf, sizeof(key_buf));

  uchar *ptr = value_buf;
  rdb_netbuf_store_uint16(ptr, Rdb_key_def::INDEX_INFO_VERSION_LATEST);
  ptr += RDB_SIZEOF_INDEX_INFO_VERSION;
  rdb_netbuf_store_byte(ptr, index_info->m_index_type);
  ptr += RDB_SIZEOF_INDEX_TYPE;
  rdb_netbuf_store_uint16(ptr, index_info->m_kv_version);
  ptr += RDB_SIZEOF_KV_VERSION;
  rdb_netbuf_store_uint32(ptr, index_info->m_index_flags);
  ptr += RDB_SIZEOF_INDEX_FLAGS;
  rdb_netbuf_store_uint64(ptr, index_info->m_ttl_duration);
  ptr += ROCKSDB_SIZEOF_TTL_RECORD;

  const rocksdb::Slice value =
      rocksdb::Slice((char *)value_buf, ptr - value_buf);
  batch->Put(m_system_cfh, key, value);
}

void Rdb_dict_manager::add_cf_flags(rocksdb::WriteBatch *const batch,
                                    const uint32_t &cf_id,
                                    const uint32_t &cf_flags) const {
  DBUG_ASSERT(batch != nullptr);

  uchar key_buf[Rdb_key_def::INDEX_NUMBER_SIZE * 2] = {0};
  uchar value_buf[Rdb_key_def::VERSION_SIZE + Rdb_key_def::INDEX_NUMBER_SIZE] =
      {0};
  rdb_netbuf_store_uint32(key_buf, Rdb_key_def::CF_DEFINITION);
  rdb_netbuf_store_uint32(key_buf + Rdb_key_def::INDEX_NUMBER_SIZE, cf_id);
  const rocksdb::Slice key = rocksdb::Slice((char *)key_buf, sizeof(key_buf));

  rdb_netbuf_store_uint16(value_buf, Rdb_key_def::CF_DEFINITION_VERSION);
  rdb_netbuf_store_uint32(value_buf + Rdb_key_def::VERSION_SIZE, cf_flags);
  const rocksdb::Slice value =
      rocksdb::Slice((char *)value_buf, sizeof(value_buf));
  batch->Put(m_system_cfh, key, value);
}

void Rdb_dict_manager::delete_index_info(rocksdb::WriteBatch *batch,
                                         const GL_INDEX_ID &gl_index_id) const {
  delete_with_prefix(batch, Rdb_key_def::INDEX_INFO, gl_index_id);
  delete_with_prefix(batch, Rdb_key_def::INDEX_STATISTICS, gl_index_id);
}

bool Rdb_dict_manager::get_index_info(
    const GL_INDEX_ID &gl_index_id,
    struct Rdb_index_info *const index_info) const {

  index_info->m_gl_index_id = gl_index_id;

  bool found = false;
  bool error = false;
  std::string value;
  uchar key_buf[Rdb_key_def::INDEX_NUMBER_SIZE * 3] = {0};
  dump_index_id(key_buf, Rdb_key_def::INDEX_INFO, gl_index_id);
  const rocksdb::Slice &key = rocksdb::Slice((char *)key_buf, sizeof(key_buf));

  const rocksdb::Status &status = get_value(key, &value);
  if (status.ok()) {
    const uchar *const val = (const uchar *)value.c_str();
    const uchar *ptr = val;
    index_info->m_index_dict_version = rdb_netbuf_to_uint16(val);
    ptr += RDB_SIZEOF_INDEX_INFO_VERSION;

    switch (index_info->m_index_dict_version) {
    case Rdb_key_def::INDEX_INFO_VERSION_FIELD_FLAGS:
      /* Sanity check to prevent reading bogus TTL record. */
      if (value.size() != RDB_SIZEOF_INDEX_INFO_VERSION +
                              RDB_SIZEOF_INDEX_TYPE + RDB_SIZEOF_KV_VERSION +
                              RDB_SIZEOF_INDEX_FLAGS +
                              ROCKSDB_SIZEOF_TTL_RECORD) {
        error = true;
        break;
      }
      index_info->m_index_type = rdb_netbuf_to_byte(ptr);
      ptr += RDB_SIZEOF_INDEX_TYPE;
      index_info->m_kv_version = rdb_netbuf_to_uint16(ptr);
      ptr += RDB_SIZEOF_KV_VERSION;
      index_info->m_index_flags = rdb_netbuf_to_uint32(ptr);
      ptr += RDB_SIZEOF_INDEX_FLAGS;
      index_info->m_ttl_duration = rdb_netbuf_to_uint64(ptr);
      found = true;
      break;

    case Rdb_key_def::INDEX_INFO_VERSION_TTL:
      /* Sanity check to prevent reading bogus into TTL record. */
      if (value.size() != RDB_SIZEOF_INDEX_INFO_VERSION +
                              RDB_SIZEOF_INDEX_TYPE + RDB_SIZEOF_KV_VERSION +
                              ROCKSDB_SIZEOF_TTL_RECORD) {
        error = true;
        break;
      }
      index_info->m_index_type = rdb_netbuf_to_byte(ptr);
      ptr += RDB_SIZEOF_INDEX_TYPE;
      index_info->m_kv_version = rdb_netbuf_to_uint16(ptr);
      ptr += RDB_SIZEOF_KV_VERSION;
      index_info->m_ttl_duration = rdb_netbuf_to_uint64(ptr);
      found = true;
      break;

    case Rdb_key_def::INDEX_INFO_VERSION_VERIFY_KV_FORMAT:
    case Rdb_key_def::INDEX_INFO_VERSION_GLOBAL_ID:
      index_info->m_index_type = rdb_netbuf_to_byte(ptr);
      ptr += RDB_SIZEOF_INDEX_TYPE;
      index_info->m_kv_version = rdb_netbuf_to_uint16(ptr);
      found = true;
      break;

    default:
      error = true;
      break;
    }

    switch (index_info->m_index_type) {
    case Rdb_key_def::INDEX_TYPE_PRIMARY:
    case Rdb_key_def::INDEX_TYPE_HIDDEN_PRIMARY: {
      error =
          index_info->m_kv_version > Rdb_key_def::PRIMARY_FORMAT_VERSION_LATEST;
      break;
    }
    case Rdb_key_def::INDEX_TYPE_SECONDARY:
      error = index_info->m_kv_version >
              Rdb_key_def::SECONDARY_FORMAT_VERSION_LATEST;
      break;
    default:
      error = true;
      break;
    }
  }

  if (error) {
    // NO_LINT_DEBUG
    sql_print_error(
        "RocksDB: Found invalid key version number (%u, %u, %u, %llu) "
        "from data dictionary. This should never happen "
        "and it may be a bug.",
        index_info->m_index_dict_version, index_info->m_index_type,
        index_info->m_kv_version, index_info->m_ttl_duration);
    abort_with_stack_traces();
  }

  return found;
}

bool Rdb_dict_manager::get_cf_flags(const uint32_t &cf_id,
                                    uint32_t *const cf_flags) const {
  DBUG_ASSERT(cf_flags != nullptr);

  bool found = false;
  std::string value;
  uchar key_buf[Rdb_key_def::INDEX_NUMBER_SIZE * 2] = {0};

  rdb_netbuf_store_uint32(key_buf, Rdb_key_def::CF_DEFINITION);
  rdb_netbuf_store_uint32(key_buf + Rdb_key_def::INDEX_NUMBER_SIZE, cf_id);

  const rocksdb::Slice key =
      rocksdb::Slice(reinterpret_cast<char *>(key_buf), sizeof(key_buf));
  const rocksdb::Status status = get_value(key, &value);

  if (status.ok()) {
    const uchar *val = (const uchar *)value.c_str();
    DBUG_ASSERT(val);

    const uint16_t version = rdb_netbuf_to_uint16(val);

    if (version == Rdb_key_def::CF_DEFINITION_VERSION) {
      *cf_flags = rdb_netbuf_to_uint32(val + Rdb_key_def::VERSION_SIZE);
      found = true;
    }
  }

  return found;
}

/*
  Returning index ids that were marked as deleted (via DROP TABLE) but
  still not removed by drop_index_thread yet, or indexes that are marked as
  ongoing creation.
 */
void Rdb_dict_manager::get_ongoing_index_operation(
    std::unordered_set<GL_INDEX_ID> *gl_index_ids,
    Rdb_key_def::DATA_DICT_TYPE dd_type) const {
  DBUG_ASSERT(dd_type == Rdb_key_def::DDL_DROP_INDEX_ONGOING ||
              dd_type == Rdb_key_def::DDL_CREATE_INDEX_ONGOING);

  uchar index_buf[Rdb_key_def::INDEX_NUMBER_SIZE];
  rdb_netbuf_store_uint32(index_buf, dd_type);
  const rocksdb::Slice index_slice(reinterpret_cast<char *>(index_buf),
                                   Rdb_key_def::INDEX_NUMBER_SIZE);

  rocksdb::Iterator *it = new_iterator();
  for (it->Seek(index_slice); it->Valid(); it->Next()) {
    rocksdb::Slice key = it->key();
    const uchar *const ptr = (const uchar *)key.data();

    /*
      Ongoing drop/create index operations require key to be of the form:
      dd_type + cf_id + index_id (== INDEX_NUMBER_SIZE * 3)

      This may need to be changed in the future if we want to process a new
      ddl_type with different format.
    */
    if (key.size() != Rdb_key_def::INDEX_NUMBER_SIZE * 3 ||
        rdb_netbuf_to_uint32(ptr) != dd_type) {
      break;
    }

    // We don't check version right now since currently we always store only
    // Rdb_key_def::DDL_DROP_INDEX_ONGOING_VERSION = 1 as a value.
    // If increasing version number, we need to add version check logic here.
    GL_INDEX_ID gl_index_id;
    gl_index_id.cf_id =
        rdb_netbuf_to_uint32(ptr + Rdb_key_def::INDEX_NUMBER_SIZE);
    gl_index_id.index_id =
        rdb_netbuf_to_uint32(ptr + 2 * Rdb_key_def::INDEX_NUMBER_SIZE);
    gl_index_ids->insert(gl_index_id);
  }
  delete it;
}

/*
  Returning true if index_id is create/delete ongoing (undergoing creation or
  marked as deleted via DROP TABLE but drop_index_thread has not wiped yet)
  or not.
 */
bool Rdb_dict_manager::is_index_operation_ongoing(
    const GL_INDEX_ID &gl_index_id, Rdb_key_def::DATA_DICT_TYPE dd_type) const {
  DBUG_ASSERT(dd_type == Rdb_key_def::DDL_DROP_INDEX_ONGOING ||
              dd_type == Rdb_key_def::DDL_CREATE_INDEX_ONGOING);

  bool found = false;
  std::string value;
  uchar key_buf[Rdb_key_def::INDEX_NUMBER_SIZE * 3] = {0};
  dump_index_id(key_buf, dd_type, gl_index_id);
  const rocksdb::Slice key = rocksdb::Slice((char *)key_buf, sizeof(key_buf));

  const rocksdb::Status status = get_value(key, &value);
  if (status.ok()) {
    found = true;
  }
  return found;
}

/*
  Adding index_id to data dictionary so that the index id is removed
  by drop_index_thread, or to track online index creation.
 */
void Rdb_dict_manager::start_ongoing_index_operation(
    rocksdb::WriteBatch *const batch, const GL_INDEX_ID &gl_index_id,
    Rdb_key_def::DATA_DICT_TYPE dd_type) const {
  DBUG_ASSERT(dd_type == Rdb_key_def::DDL_DROP_INDEX_ONGOING ||
              dd_type == Rdb_key_def::DDL_CREATE_INDEX_ONGOING);

  uchar key_buf[Rdb_key_def::INDEX_NUMBER_SIZE * 3] = {0};
  uchar value_buf[Rdb_key_def::VERSION_SIZE] = {0};
  dump_index_id(key_buf, dd_type, gl_index_id);

  // version as needed
  if (dd_type == Rdb_key_def::DDL_DROP_INDEX_ONGOING) {
    rdb_netbuf_store_uint16(value_buf,
                            Rdb_key_def::DDL_DROP_INDEX_ONGOING_VERSION);
  } else {
    rdb_netbuf_store_uint16(value_buf,
                            Rdb_key_def::DDL_CREATE_INDEX_ONGOING_VERSION);
  }

  const rocksdb::Slice key = rocksdb::Slice((char *)key_buf, sizeof(key_buf));
  const rocksdb::Slice value =
      rocksdb::Slice((char *)value_buf, sizeof(value_buf));
  batch->Put(m_system_cfh, key, value);
}

/*
  Removing index_id from data dictionary to confirm drop_index_thread
  completed dropping entire key/values of the index_id
 */
void Rdb_dict_manager::end_ongoing_index_operation(
    rocksdb::WriteBatch *const batch, const GL_INDEX_ID &gl_index_id,
    Rdb_key_def::DATA_DICT_TYPE dd_type) const {
  DBUG_ASSERT(dd_type == Rdb_key_def::DDL_DROP_INDEX_ONGOING ||
              dd_type == Rdb_key_def::DDL_CREATE_INDEX_ONGOING);

  delete_with_prefix(batch, dd_type, gl_index_id);
}

/*
  Returning true if there is no target index ids to be removed
  by drop_index_thread
 */
bool Rdb_dict_manager::is_drop_index_empty() const {
  std::unordered_set<GL_INDEX_ID> gl_index_ids;
  get_ongoing_drop_indexes(&gl_index_ids);
  return gl_index_ids.empty();
}

/*
  This function is supposed to be called by DROP TABLE. Logging messages
  that dropping indexes started, and adding data dictionary so that
  all associated indexes to be removed
 */
void Rdb_dict_manager::add_drop_table(
    std::shared_ptr<Rdb_key_def> *const key_descr, const uint32 &n_keys,
    rocksdb::WriteBatch *const batch) const {
  std::unordered_set<GL_INDEX_ID> dropped_index_ids;
  for (uint32 i = 0; i < n_keys; i++) {
    dropped_index_ids.insert(key_descr[i]->get_gl_index_id());
  }

  add_drop_index(dropped_index_ids, batch);
}

/*
  Called during inplace index drop operations. Logging messages
  that dropping indexes started, and adding data dictionary so that
  all associated indexes to be removed
 */
void Rdb_dict_manager::add_drop_index(
    const std::unordered_set<GL_INDEX_ID> &gl_index_ids,
    rocksdb::WriteBatch *const batch) const {
  for (const auto &gl_index_id : gl_index_ids) {
    log_start_drop_index(gl_index_id, "Begin");
    start_drop_index(batch, gl_index_id);
  }
}

/*
  Called during inplace index creation operations. Logging messages
  that adding indexes started, and updates data dictionary with all associated
  indexes to be added.
 */
void Rdb_dict_manager::add_create_index(
    const std::unordered_set<GL_INDEX_ID> &gl_index_ids,
    rocksdb::WriteBatch *const batch) const {
  for (const auto &gl_index_id : gl_index_ids) {
    // NO_LINT_DEBUG
    sql_print_information("RocksDB: Begin index creation (%u,%u)",
                          gl_index_id.cf_id, gl_index_id.index_id);
    start_create_index(batch, gl_index_id);
  }
}

/*
  This function is supposed to be called by drop_index_thread, when it
  finished dropping any index, or at the completion of online index creation.
 */
void Rdb_dict_manager::finish_indexes_operation(
    const std::unordered_set<GL_INDEX_ID> &gl_index_ids,
    Rdb_key_def::DATA_DICT_TYPE dd_type) const {
  DBUG_ASSERT(dd_type == Rdb_key_def::DDL_DROP_INDEX_ONGOING ||
              dd_type == Rdb_key_def::DDL_CREATE_INDEX_ONGOING);

  const std::unique_ptr<rocksdb::WriteBatch> wb = begin();
  rocksdb::WriteBatch *const batch = wb.get();

  std::unordered_set<GL_INDEX_ID> incomplete_create_indexes;
  get_ongoing_create_indexes(&incomplete_create_indexes);

  for (const auto &gl_index_id : gl_index_ids) {
    if (is_index_operation_ongoing(gl_index_id, dd_type)) {
      end_ongoing_index_operation(batch, gl_index_id, dd_type);

      /*
        Remove the corresponding incomplete create indexes from data
        dictionary as well
      */
      if (dd_type == Rdb_key_def::DDL_DROP_INDEX_ONGOING) {
        if (incomplete_create_indexes.count(gl_index_id)) {
          end_ongoing_index_operation(batch, gl_index_id,
                                      Rdb_key_def::DDL_CREATE_INDEX_ONGOING);
        }
      }
    }

    if (dd_type == Rdb_key_def::DDL_DROP_INDEX_ONGOING) {
      delete_index_info(batch, gl_index_id);
    }
  }
  commit(batch);
}

/*
  This function is supposed to be called when initializing
  Rdb_dict_manager (at startup). If there is any index ids that are
  drop ongoing, printing out messages for diagnostics purposes.
 */
void Rdb_dict_manager::resume_drop_indexes() const {
  std::unordered_set<GL_INDEX_ID> gl_index_ids;
  get_ongoing_drop_indexes(&gl_index_ids);

  uint max_index_id_in_dict = 0;
  get_max_index_id(&max_index_id_in_dict);

  for (const auto &gl_index_id : gl_index_ids) {
    log_start_drop_index(gl_index_id, "Resume");
    if (max_index_id_in_dict < gl_index_id.index_id) {
      sql_print_error("RocksDB: Found max index id %u from data dictionary "
                      "but also found dropped index id (%u,%u) from drop_index "
                      "dictionary. This should never happen and is possibly a "
                      "bug.",
                      max_index_id_in_dict, gl_index_id.cf_id,
                      gl_index_id.index_id);
      abort_with_stack_traces();
    }
  }
}

void Rdb_dict_manager::rollback_ongoing_index_creation() const {
  const std::unique_ptr<rocksdb::WriteBatch> wb = begin();
  rocksdb::WriteBatch *const batch = wb.get();

  std::unordered_set<GL_INDEX_ID> gl_index_ids;
  get_ongoing_create_indexes(&gl_index_ids);

  for (const auto &gl_index_id : gl_index_ids) {
    // NO_LINT_DEBUG
    sql_print_information("RocksDB: Removing incomplete create index (%u,%u)",
                          gl_index_id.cf_id, gl_index_id.index_id);

    start_drop_index(batch, gl_index_id);
  }

  commit(batch);
}

void Rdb_dict_manager::log_start_drop_table(
    const std::shared_ptr<Rdb_key_def> *const key_descr, const uint32 &n_keys,
    const char *const log_action) const {
  for (uint32 i = 0; i < n_keys; i++) {
    log_start_drop_index(key_descr[i]->get_gl_index_id(), log_action);
  }
}

void Rdb_dict_manager::log_start_drop_index(GL_INDEX_ID gl_index_id,
                                            const char *log_action) const {
  struct Rdb_index_info index_info;
  if (!get_index_info(gl_index_id, &index_info)) {
    /*
      If we don't find the index info, it could be that it's because it was a
      partially created index that isn't in the data dictionary yet that needs
      to be rolled back.
    */
    std::unordered_set<GL_INDEX_ID> incomplete_create_indexes;
    get_ongoing_create_indexes(&incomplete_create_indexes);

    if (!incomplete_create_indexes.count(gl_index_id)) {
      /* If it's not a partially created index, something is very wrong. */
      sql_print_error("RocksDB: Failed to get column family info "
                      "from index id (%u,%u). MyRocks data dictionary may "
                      "get corrupted.",
                      gl_index_id.cf_id, gl_index_id.index_id);
      abort_with_stack_traces();
    }
  }
}

bool Rdb_dict_manager::get_max_index_id(uint32_t *const index_id) const {
  bool found = false;
  std::string value;

  const rocksdb::Status status = get_value(m_key_slice_max_index_id, &value);
  if (status.ok()) {
    const uchar *const val = (const uchar *)value.c_str();
    const uint16_t &version = rdb_netbuf_to_uint16(val);
    if (version == Rdb_key_def::MAX_INDEX_ID_VERSION) {
      *index_id = rdb_netbuf_to_uint32(val + Rdb_key_def::VERSION_SIZE);
      found = true;
    }
  }
  return found;
}

bool Rdb_dict_manager::update_max_index_id(rocksdb::WriteBatch *const batch,
                                           const uint32_t &index_id) const {
  DBUG_ASSERT(batch != nullptr);

  uint32_t old_index_id = -1;
  if (get_max_index_id(&old_index_id)) {
    if (old_index_id > index_id) {
      sql_print_error("RocksDB: Found max index id %u from data dictionary "
                      "but trying to update to older value %u. This should "
                      "never happen and possibly a bug.",
                      old_index_id, index_id);
      return true;
    }
  }

  uchar value_buf[Rdb_key_def::VERSION_SIZE + Rdb_key_def::INDEX_NUMBER_SIZE] =
      {0};
  rdb_netbuf_store_uint16(value_buf, Rdb_key_def::MAX_INDEX_ID_VERSION);
  rdb_netbuf_store_uint32(value_buf + Rdb_key_def::VERSION_SIZE, index_id);
  const rocksdb::Slice value =
      rocksdb::Slice((char *)value_buf, sizeof(value_buf));
  batch->Put(m_system_cfh, m_key_slice_max_index_id, value);
  return false;
}

void Rdb_dict_manager::add_stats(
    rocksdb::WriteBatch *const batch,
    const std::vector<Rdb_index_stats> &stats) const {
  DBUG_ASSERT(batch != nullptr);

  for (const auto &it : stats) {
    uchar key_buf[Rdb_key_def::INDEX_NUMBER_SIZE * 3] = {0};
    dump_index_id(key_buf, Rdb_key_def::INDEX_STATISTICS, it.m_gl_index_id);

    // IndexStats::materialize takes complete care of serialization including
    // storing the version
    const auto value =
        Rdb_index_stats::materialize(std::vector<Rdb_index_stats>{it}, 1.);

    batch->Put(m_system_cfh, rocksdb::Slice((char *)key_buf, sizeof(key_buf)),
               value);
  }
}

Rdb_index_stats Rdb_dict_manager::get_stats(GL_INDEX_ID gl_index_id) const {
  uchar key_buf[Rdb_key_def::INDEX_NUMBER_SIZE * 3] = {0};
  dump_index_id(key_buf, Rdb_key_def::INDEX_STATISTICS, gl_index_id);

  std::string value;
  const rocksdb::Status status = get_value(
      rocksdb::Slice(reinterpret_cast<char *>(key_buf), sizeof(key_buf)),
      &value);
  if (status.ok()) {
    std::vector<Rdb_index_stats> v;
    // unmaterialize checks if the version matches
    if (Rdb_index_stats::unmaterialize(value, &v) == 0 && v.size() == 1) {
      return v[0];
    }
  }

  return Rdb_index_stats();
}

uint Rdb_seq_generator::get_and_update_next_number(
    Rdb_dict_manager *const dict) {
  DBUG_ASSERT(dict != nullptr);

  uint res;
  RDB_MUTEX_LOCK_CHECK(m_mutex);

  res = m_next_number++;

  const std::unique_ptr<rocksdb::WriteBatch> wb = dict->begin();
  rocksdb::WriteBatch *const batch = wb.get();

  DBUG_ASSERT(batch != nullptr);
  dict->update_max_index_id(batch, res);
  dict->commit(batch);

  RDB_MUTEX_UNLOCK_CHECK(m_mutex);

  return res;
}

} // namespace myrocks