File: histograms-t.cc

package info (click to toggle)
mysql-8.0 8.0.43-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,273,924 kB
  • sloc: cpp: 4,684,605; ansic: 412,450; pascal: 108,398; java: 83,641; perl: 30,221; cs: 27,067; sql: 26,594; sh: 24,181; python: 21,816; yacc: 17,169; php: 11,522; xml: 7,388; javascript: 7,076; makefile: 2,194; lex: 1,075; awk: 670; asm: 520; objc: 183; ruby: 97; lisp: 86
file content (2420 lines) | stat: -rw-r--r-- 94,948 bytes parent folder | download
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
/* Copyright (c) 2016, 2025, Oracle and/or its affiliates.

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

   This program is designed to work with certain software (including
   but not limited to OpenSSL) that is licensed under separate terms,
   as designated in a particular file or component or in included license
   documentation.  The authors of MySQL hereby grant you an additional
   permission to link the program and your derivative works with the
   separately licensed software that they have either included with
   the program or referenced in the documentation.

   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, version 2.0, for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */

#include <gtest/gtest.h>
#include <limits>  // std::numeric_limits
#include <map>     // std::map
#include <string>  // std::string

#include "lex_string.h"
#include "m_ctype.h"  // my_charset_latin1, my_charset_bin
#include "my_inttypes.h"
#include "my_systime.h"                  // my_micro_time()
#include "my_time.h"                     // MYSQL_TIME
#include "sql-common/json_dom.h"         // Json_object
#include "sql/field.h"                   // my_charset_numeric
#include "sql/histograms/equi_height.h"  // Equi_height
#include "sql/histograms/histogram.h"    // Histogram, Histogram_comparator
#include "sql/histograms/singleton.h"    // Singleton
#include "sql/histograms/value_map.h"    // Value_map<T>
#include "sql/my_decimal.h"              // my_decimal
#include "sql/sql_time.h"                // my_time_compare
#include "sql/tztime.h"                  // my_tz_UTC
#include "template_utils.h"              // down_cast

namespace histograms_unittest {

using namespace histograms;

class HistogramsTest : public ::testing::Test {
 protected:
  MEM_ROOT m_mem_root;

  Value_map<double> double_values;
  Value_map<String> string_values;
  Value_map<ulonglong> uint_values;
  Value_map<longlong> int_values;
  Value_map<my_decimal> decimal_values;
  Value_map<MYSQL_TIME> datetime_values;
  Value_map<MYSQL_TIME> date_values;
  Value_map<MYSQL_TIME> time_values;
  Value_map<String> blob_values;

  /*
    Declare these arrays here, so that they survive the lifetime of the unit
    tests.

    Do not use negative char values, since these will be cast to an uchar
    pointer in the function sortcmp.
  */
  const char blob_buf1[4] = {0, 0, 0, 0};
  const char blob_buf2[4] = {127, 127, 127, 127};

 public:
  HistogramsTest()
      : m_mem_root(PSI_NOT_INSTRUMENTED, 256),
        double_values(&my_charset_numeric, Value_map_type::DOUBLE),
        string_values(&my_charset_latin1, Value_map_type::STRING),
        uint_values(&my_charset_numeric, Value_map_type::UINT),
        int_values(&my_charset_numeric, Value_map_type::INT),
        decimal_values(&my_charset_numeric, Value_map_type::DECIMAL),
        datetime_values(&my_charset_numeric, Value_map_type::DATETIME),
        date_values(&my_charset_numeric, Value_map_type::DATE),
        time_values(&my_charset_numeric, Value_map_type::TIME),
        blob_values(&my_charset_bin, Value_map_type::STRING) {
    // Double values.
    double_values.add_values(std::numeric_limits<double>::lowest(), 10);
    double_values.add_values(std::numeric_limits<double>::max(), 10);
    double_values.add_values(std::numeric_limits<double>::epsilon(), 10);
    double_values.add_values(0.0, 10);
    double_values.add_values(42.0, 10);
    double_values.add_values(43.0, 10);

    // String values.
    string_values.add_values(String("", &my_charset_latin1), 10);
    string_values.add_values(String("string4", &my_charset_latin1), 10);
    string_values.add_values(String("string3", &my_charset_latin1), 10);
    string_values.add_values(String("string1", &my_charset_latin1), 10);
    string_values.add_values(String("string2", &my_charset_latin1), 10);

    // Unsigned integer values (ulonglong).
    uint_values.add_values(std::numeric_limits<ulonglong>::lowest(), 10);
    uint_values.add_values(std::numeric_limits<ulonglong>::max(), 10);
    uint_values.add_values(42ULL, 10);
    uint_values.add_values(43ULL, 10);
    uint_values.add_values(10000ULL, 10);

    // Signed integer values (longlong).
    int_values.add_values(std::numeric_limits<longlong>::lowest(), 10);
    int_values.add_values(std::numeric_limits<longlong>::max(), 10);
    int_values.add_values(0LL, 10);
    int_values.add_values(-1LL, 10);
    int_values.add_values(1LL, 10);
    int_values.add_values(42LL, 10);
    int_values.add_values(10000LL, 10);

    // Decimal values (my_decimal).
    my_decimal decimal1;
    int2my_decimal(E_DEC_FATAL_ERROR, 0LL, false, &decimal1);
    decimal_values.add_values(decimal1, 10);

    my_decimal decimal2;
    int2my_decimal(E_DEC_FATAL_ERROR, -1000LL, false, &decimal2);
    decimal_values.add_values(decimal2, 10);

    my_decimal decimal3;
    int2my_decimal(E_DEC_FATAL_ERROR, 1000LL, false, &decimal3);
    decimal_values.add_values(decimal3, 10);

    my_decimal decimal4;
    int2my_decimal(E_DEC_FATAL_ERROR, 42LL, false, &decimal4);
    decimal_values.add_values(decimal4, 10);

    my_decimal decimal5;
    int2my_decimal(E_DEC_FATAL_ERROR, 1LL, false, &decimal5);
    decimal_values.add_values(decimal5, 10);

    /*
      Datetime values (MYSQL_TIME).

      We are using these packed values for testing:

      914866242077065216  => 1000-01-01 00:00:00.000000
      914866242077065217  => 1000-01-01 00:00:00.000001
      1845541820734373888 => 2017-05-23 08:08:03.000000
      9147936188962652735 => 9999-12-31 23:59:59.999999
      9147936188962652734 => 9999-12-31 23:59:59.999998
    */
    MYSQL_TIME datetime1;
    TIME_from_longlong_datetime_packed(&datetime1, 9147936188962652734);
    datetime_values.add_values(datetime1, 10);

    MYSQL_TIME datetime2;
    TIME_from_longlong_datetime_packed(&datetime2, 914866242077065217);
    datetime_values.add_values(datetime2, 10);

    MYSQL_TIME datetime3;
    TIME_from_longlong_datetime_packed(&datetime3, 914866242077065216);
    datetime_values.add_values(datetime3, 10);

    MYSQL_TIME datetime4;
    TIME_from_longlong_datetime_packed(&datetime4, 1845541820734373888);
    datetime_values.add_values(datetime4, 10);

    MYSQL_TIME datetime5;
    TIME_from_longlong_datetime_packed(&datetime5, 9147936188962652735);
    datetime_values.add_values(datetime5, 10);

    /*
      Date values (MYSQL_TIME).

      Do not test negative values, since negative DATETIME is not supported by
      MySQL. We also call "set_zero_time", to initialize the entire MYSQL_TIME
      structure. If we don't, valgrind will complain on uninitialised values.
    */
    MYSQL_TIME date1;
    set_zero_time(&date1, MYSQL_TIMESTAMP_DATE);
    set_max_hhmmss(&date1);
    date_values.add_values(date1, 10);

    MYSQL_TIME date2;
    set_zero_time(&date2, MYSQL_TIMESTAMP_DATE);
    TIME_from_longlong_date_packed(&date2, 10000);
    date_values.add_values(date2, 10);

    MYSQL_TIME date3;
    set_zero_time(&date3, MYSQL_TIMESTAMP_DATE);
    TIME_from_longlong_date_packed(&date3, 0);
    date_values.add_values(date3, 10);

    MYSQL_TIME date4;
    set_zero_time(&date4, MYSQL_TIMESTAMP_DATE);
    TIME_from_longlong_date_packed(&date4, 100);
    date_values.add_values(date4, 10);

    MYSQL_TIME date5;
    set_zero_time(&date5, MYSQL_TIMESTAMP_DATE);
    TIME_from_longlong_date_packed(&date5, 100000);
    date_values.add_values(date5, 10);

    /*
      Time values (MYSQL_TIME).

      Do not test negative values, since negative DATETIME is not supported by
      MySQL.
    */
    MYSQL_TIME time1;
    set_zero_time(&time1, MYSQL_TIMESTAMP_TIME);
    set_max_time(&time1, false);
    time_values.add_values(time1, 10);

    MYSQL_TIME time2;
    set_zero_time(&time2, MYSQL_TIMESTAMP_TIME);
    TIME_from_longlong_time_packed(&time2, 12);
    time_values.add_values(time2, 10);

    MYSQL_TIME time3;
    set_zero_time(&time3, MYSQL_TIMESTAMP_TIME);
    TIME_from_longlong_time_packed(&time3, 0);
    time_values.add_values(time3, 10);

    MYSQL_TIME time4;
    set_zero_time(&time4, MYSQL_TIMESTAMP_TIME);
    TIME_from_longlong_time_packed(&time4, 42);
    time_values.add_values(time4, 10);

    MYSQL_TIME time5;
    set_zero_time(&time5, MYSQL_TIMESTAMP_TIME);
    TIME_from_longlong_time_packed(&time5, 100000);
    time_values.add_values(time5, 10);

    // Blob values.
    blob_values.add_values(String(blob_buf1, 4, &my_charset_bin), 10);
    blob_values.add_values(String(blob_buf2, 4, &my_charset_bin), 10);
    blob_values.add_values(String("foo", &my_charset_bin), 10);
    blob_values.add_values(String("bar", &my_charset_bin), 10);
    blob_values.add_values(String("foobar", &my_charset_bin), 10);
  }
};

/*
  Utility function that verify the following properties for a histogram that is
  converted to JSON:
    - All histogram types must have the field "last-updated" of type J_DATETIME.
    - All histogram types must have the field "histogram-type" of type J_STRING.
      * Check that the printed histogram type actually is the correct one.
    - All histogram types must have the field "buckets" of type J_ARRAY.
      * Check that the number of buckets in the JSON array is the same as the
        amount of buckets in the original histogram.
    - All histogram types must have the field "null-values" of type J_DOUBLE.
    - All histogram types must have the field "collation-id" of type J_UINT.
*/
void VerifyCommonJSONFields(Json_object *json_histogram,
                            const Histogram *histogram) {
  ASSERT_TRUE(histogram != nullptr);

  // Last updated field.
  Json_dom *last_updated_dom = json_histogram->get("last-updated");
  EXPECT_NE(last_updated_dom, nullptr);
  EXPECT_EQ(last_updated_dom->json_type(), enum_json_type::J_DATETIME);

  // Histogram type field.
  Json_dom *histogram_type_dom = json_histogram->get("histogram-type");
  EXPECT_NE(histogram_type_dom, nullptr);
  EXPECT_EQ(histogram_type_dom->json_type(), enum_json_type::J_STRING);

  Json_string *json_histogram_type =
      static_cast<Json_string *>(histogram_type_dom);

  switch (histogram->get_histogram_type()) {
    case Histogram::enum_histogram_type::EQUI_HEIGHT:
      EXPECT_STREQ(json_histogram_type->value().c_str(), "equi-height");
      break;
    case Histogram::enum_histogram_type::SINGLETON:
      EXPECT_STREQ(json_histogram_type->value().c_str(), "singleton");
      break;
  }

  // Buckets field.
  Json_dom *buckets_dom = json_histogram->get("buckets");
  EXPECT_NE(buckets_dom, nullptr);
  EXPECT_EQ(buckets_dom->json_type(), enum_json_type::J_ARRAY);

  // Fraction of null values.
  Json_dom *null_values_dom = json_histogram->get("null-values");
  EXPECT_NE(null_values_dom, nullptr);
  EXPECT_EQ(null_values_dom->json_type(), enum_json_type::J_DOUBLE);

  // Collation ID
  Json_dom *collation_id_dom = json_histogram->get("collation-id");
  EXPECT_NE(collation_id_dom, nullptr);
  EXPECT_EQ(collation_id_dom->json_type(), enum_json_type::J_UINT);

  Json_array *buckets = static_cast<Json_array *>(buckets_dom);
  EXPECT_EQ(buckets->size(), histogram->get_num_buckets());
}

/*
  Utility function that verifies the following constraints for a singleton
  histogram that is converted to JSON:
    - The value in a singleton bucket is greater than or equal to the value in
      the previous bucket.
    - The cumulative frequency is in the range (0.0, 1.0] (lower exclusive,
      upper inclusive).
    - The cumulative frequency is greater than the cumulative frequency in the
      previous bucket.
*/
void VerifySingletonBucketConstraintsDouble(const Histogram *histogram) {
  ASSERT_TRUE(histogram != nullptr);

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *buckets = down_cast<Json_array *>(buckets_dom);

  double previous_value = 0.0;
  double previous_cumulative_frequency = 0.0;
  for (size_t i = 0; i < buckets->size(); ++i) {
    Json_dom *bucket_dom = (*buckets)[i];
    Json_array *bucket = static_cast<Json_array *>(bucket_dom);

    Json_double *json_frequency = down_cast<Json_double *>((*bucket)[1]);
    double current_cumulative_frequency = json_frequency->value();
    EXPECT_GT(current_cumulative_frequency, 0.0);
    EXPECT_LE(current_cumulative_frequency, 1.0);

    Json_double *json_double = down_cast<Json_double *>((*bucket)[0]);
    double current_value = json_double->value();
    if (i > 0) {
      EXPECT_TRUE(Histogram_comparator()(previous_value, current_value));
      EXPECT_LT(previous_cumulative_frequency, current_cumulative_frequency);
    }
    previous_value = current_value;
    previous_cumulative_frequency = current_cumulative_frequency;
  }
}

void VerifySingletonBucketConstraintsInt(Histogram *histogram) {
  ASSERT_TRUE(histogram != nullptr);

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *buckets = down_cast<Json_array *>(buckets_dom);

  longlong previous_value = 0;
  double previous_cumulative_frequency = 0.0;
  for (size_t i = 0; i < buckets->size(); ++i) {
    Json_dom *bucket_dom = (*buckets)[i];
    Json_array *bucket = static_cast<Json_array *>(bucket_dom);

    Json_double *json_frequency = down_cast<Json_double *>((*bucket)[1]);
    double current_cumulative_frequency = json_frequency->value();
    EXPECT_GT(current_cumulative_frequency, 0.0);
    EXPECT_LE(current_cumulative_frequency, 1.0);

    Json_int *json_int = down_cast<Json_int *>((*bucket)[0]);
    longlong current_value = json_int->value();
    if (i > 0) {
      EXPECT_TRUE(Histogram_comparator()(previous_value, current_value));
      EXPECT_LT(previous_cumulative_frequency, current_cumulative_frequency);
    }
    previous_value = current_value;
    previous_cumulative_frequency = current_cumulative_frequency;
  }
}

void VerifySingletonBucketConstraintsUInt(Histogram *histogram) {
  ASSERT_TRUE(histogram != nullptr);

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *buckets = down_cast<Json_array *>(buckets_dom);

  ulonglong previous_value = 0;
  double previous_cumulative_frequency = 0.0;
  for (size_t i = 0; i < buckets->size(); ++i) {
    Json_dom *bucket_dom = (*buckets)[i];
    Json_array *bucket = static_cast<Json_array *>(bucket_dom);

    Json_double *json_frequency = down_cast<Json_double *>((*bucket)[1]);
    double current_cumulative_frequency = json_frequency->value();
    EXPECT_GT(current_cumulative_frequency, 0.0);
    EXPECT_LE(current_cumulative_frequency, 1.0);

    Json_uint *json_uint = down_cast<Json_uint *>((*bucket)[0]);
    ulonglong current_value = json_uint->value();
    if (i > 0) {
      EXPECT_TRUE(Histogram_comparator()(previous_value, current_value));
      EXPECT_LT(previous_cumulative_frequency, current_cumulative_frequency);
    }
    previous_value = current_value;
    previous_cumulative_frequency = current_cumulative_frequency;
  }
}

void VerifySingletonBucketConstraintsString(Histogram *histogram,
                                            const CHARSET_INFO *charset) {
  ASSERT_TRUE(histogram != nullptr);

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *buckets = down_cast<Json_array *>(buckets_dom);

  String previous_value;
  double previous_cumulative_frequency = 0.0;
  for (size_t i = 0; i < buckets->size(); ++i) {
    Json_dom *bucket_dom = (*buckets)[i];
    Json_array *bucket = static_cast<Json_array *>(bucket_dom);

    Json_double *json_frequency = down_cast<Json_double *>((*bucket)[1]);
    double current_cumulative_frequency = json_frequency->value();
    EXPECT_GT(current_cumulative_frequency, 0.0);
    EXPECT_LE(current_cumulative_frequency, 1.0);

    Json_opaque *json_opaque = down_cast<Json_opaque *>((*bucket)[0]);
    String current_value(json_opaque->value(), json_opaque->size(), charset);
    if (i > 0) {
      EXPECT_TRUE(Histogram_comparator()(previous_value, current_value));
      EXPECT_LT(previous_cumulative_frequency, current_cumulative_frequency);
    }
    previous_value = current_value;
    previous_cumulative_frequency = current_cumulative_frequency;
  }
}

void VerifySingletonBucketConstraintsDecimal(Histogram *histogram) {
  ASSERT_TRUE(histogram != nullptr);

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *buckets = down_cast<Json_array *>(buckets_dom);

  const my_decimal *previous_value = nullptr;
  double previous_cumulative_frequency = 0.0;
  for (size_t i = 0; i < buckets->size(); ++i) {
    Json_dom *bucket_dom = (*buckets)[i];
    Json_array *bucket = static_cast<Json_array *>(bucket_dom);

    Json_double *json_frequency = down_cast<Json_double *>((*bucket)[1]);
    double current_cumulative_frequency = json_frequency->value();
    EXPECT_GT(current_cumulative_frequency, 0.0);
    EXPECT_LE(current_cumulative_frequency, 1.0);

    Json_decimal *json_decimal = down_cast<Json_decimal *>((*bucket)[0]);
    const my_decimal *current_value = json_decimal->value();
    if (i > 0) {
      EXPECT_TRUE(Histogram_comparator()(*previous_value, *current_value));
      EXPECT_LT(previous_cumulative_frequency, current_cumulative_frequency);
    }
    previous_value = current_value;
    previous_cumulative_frequency = current_cumulative_frequency;
  }
}

void VerifySingletonBucketConstraintsTemporal(Histogram *histogram) {
  ASSERT_TRUE(histogram != nullptr);

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *buckets = down_cast<Json_array *>(buckets_dom);

  const MYSQL_TIME *previous_value = nullptr;
  double previous_cumulative_frequency = 0.0;
  for (size_t i = 0; i < buckets->size(); ++i) {
    Json_dom *bucket_dom = (*buckets)[i];
    Json_array *bucket = static_cast<Json_array *>(bucket_dom);

    Json_double *json_frequency = down_cast<Json_double *>((*bucket)[1]);
    double current_cumulative_frequency = json_frequency->value();
    EXPECT_GT(current_cumulative_frequency, 0.0);
    EXPECT_LE(current_cumulative_frequency, 1.0);

    Json_datetime *json_datetime = down_cast<Json_datetime *>((*bucket)[0]);
    const MYSQL_TIME *current_value = json_datetime->value();
    if (i > 0) {
      EXPECT_TRUE(Histogram_comparator()(*previous_value, *current_value));
      EXPECT_LT(previous_cumulative_frequency, current_cumulative_frequency);
    }
    previous_value = current_value;
    previous_cumulative_frequency = current_cumulative_frequency;
  }
}

/*
  Utility function that verifies the following constraints for an equi-height
  histogram that is converted to JSON:
    - The lower inclusive value in an equi-height bucket is less than or equal
      to the upper inclusive value.
    - The lower inclusive value in an equi-height bucket is greater than the
      upper inclusive value of the previous bucket.
    - The cumulative frequency is in the range (0.0, 1.0] (lower exclusive,
      upper inclusive).
    - The cumulative frequency is greater than the cumulative frequency in the
      previous bucket.
    - The number of distinct values in a bucket is equal to or greater than 1.
*/
void VerifyEquiHeightBucketConstraintsDouble(Histogram *histogram) {
  ASSERT_TRUE(histogram != nullptr);

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *buckets = down_cast<Json_array *>(buckets_dom);

  double previous_upper_value = 0.0;
  double previous_cumulative_frequency = 0.0;
  for (size_t i = 0; i < buckets->size(); ++i) {
    Json_dom *bucket_dom = (*buckets)[i];
    Json_array *bucket = static_cast<Json_array *>(bucket_dom);

    Json_double *json_frequency = down_cast<Json_double *>((*bucket)[2]);
    double current_cumulative_frequency = json_frequency->value();
    EXPECT_GT(current_cumulative_frequency, 0.0);
    EXPECT_LE(current_cumulative_frequency, 1.0);

    Json_uint *json_num_distinct = down_cast<Json_uint *>((*bucket)[3]);
    EXPECT_GE(json_num_distinct->value(), 1ULL);

    /*
      Index 1 should be lower inclusive value, and index 2 should be upper
      inclusive value.
    */
    Json_double *json_double_lower = down_cast<Json_double *>((*bucket)[0]);
    Json_double *json_double_upper = down_cast<Json_double *>((*bucket)[1]);

    double current_lower_value = json_double_lower->value();
    double current_upper_value = json_double_upper->value();
    if (i > 0) {
      EXPECT_TRUE(
          Histogram_comparator()(previous_upper_value, current_lower_value));
      EXPECT_LT(previous_cumulative_frequency, current_cumulative_frequency);
    }

    EXPECT_FALSE(
        Histogram_comparator()(current_upper_value, current_lower_value));

    previous_upper_value = current_upper_value;
    previous_cumulative_frequency = current_cumulative_frequency;
  }
}

void VerifyEquiHeightBucketConstraintsInt(Histogram *histogram) {
  ASSERT_TRUE(histogram != nullptr);

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *buckets = down_cast<Json_array *>(buckets_dom);

  longlong previous_upper_value = 0;
  double previous_cumulative_frequency = 0.0;
  for (size_t i = 0; i < buckets->size(); ++i) {
    Json_dom *bucket_dom = (*buckets)[i];
    Json_array *bucket = static_cast<Json_array *>(bucket_dom);

    Json_double *json_frequency = down_cast<Json_double *>((*bucket)[2]);
    double current_cumulative_frequency = json_frequency->value();
    EXPECT_GT(current_cumulative_frequency, 0.0);
    EXPECT_LE(current_cumulative_frequency, 1.0);

    Json_uint *json_num_distinct = down_cast<Json_uint *>((*bucket)[3]);
    EXPECT_GE(json_num_distinct->value(), 1ULL);

    /*
      Index 1 should be lower inclusive value, and index 2 should be upper
      inclusive value.
    */
    Json_int *json_int_lower = down_cast<Json_int *>((*bucket)[0]);
    Json_int *json_int_upper = down_cast<Json_int *>((*bucket)[1]);

    longlong current_lower_value = json_int_lower->value();
    longlong current_upper_value = json_int_upper->value();
    if (i > 0) {
      EXPECT_TRUE(
          Histogram_comparator()(previous_upper_value, current_lower_value));
      EXPECT_LT(previous_cumulative_frequency, current_cumulative_frequency);
    }

    EXPECT_FALSE(
        Histogram_comparator()(current_upper_value, current_lower_value));

    previous_upper_value = current_upper_value;
    previous_cumulative_frequency = current_cumulative_frequency;
  }
}

void VerifyEquiHeightBucketConstraintsUInt(Histogram *histogram) {
  ASSERT_TRUE(histogram != nullptr);

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *buckets = down_cast<Json_array *>(buckets_dom);

  ulonglong previous_upper_value = 0;
  double previous_cumulative_frequency = 0.0;
  for (size_t i = 0; i < buckets->size(); ++i) {
    Json_dom *bucket_dom = (*buckets)[i];
    Json_array *bucket = static_cast<Json_array *>(bucket_dom);

    Json_double *json_frequency = down_cast<Json_double *>((*bucket)[2]);
    double current_cumulative_frequency = json_frequency->value();
    EXPECT_GT(current_cumulative_frequency, 0.0);
    EXPECT_LE(current_cumulative_frequency, 1.0);

    Json_uint *json_num_distinct = down_cast<Json_uint *>((*bucket)[3]);
    EXPECT_GE(json_num_distinct->value(), 1ULL);

    /*
      Index 1 should be lower inclusive value, and index 2 should be upper
      inclusive value.
    */
    Json_uint *json_uint_lower = down_cast<Json_uint *>((*bucket)[0]);
    Json_uint *json_uint_upper = down_cast<Json_uint *>((*bucket)[1]);

    ulonglong current_lower_value = json_uint_lower->value();
    ulonglong current_upper_value = json_uint_upper->value();
    if (i > 0) {
      EXPECT_TRUE(
          Histogram_comparator()(previous_upper_value, current_lower_value));
      EXPECT_LT(previous_cumulative_frequency, current_cumulative_frequency);
    }

    EXPECT_FALSE(
        Histogram_comparator()(current_upper_value, current_lower_value));

    previous_upper_value = current_upper_value;
    previous_cumulative_frequency = current_cumulative_frequency;
  }
}

void VerifyEquiHeightBucketConstraintsString(Histogram *histogram,
                                             const CHARSET_INFO *charset) {
  ASSERT_TRUE(histogram != nullptr);

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *buckets = down_cast<Json_array *>(buckets_dom);

  String previous_upper_value;
  double previous_cumulative_frequency = 0.0;
  for (size_t i = 0; i < buckets->size(); ++i) {
    Json_dom *bucket_dom = (*buckets)[i];
    Json_array *bucket = static_cast<Json_array *>(bucket_dom);

    Json_double *json_frequency = down_cast<Json_double *>((*bucket)[2]);
    double current_cumulative_frequency = json_frequency->value();
    EXPECT_GT(current_cumulative_frequency, 0.0);
    EXPECT_LE(current_cumulative_frequency, 1.0);

    Json_uint *json_num_distinct = down_cast<Json_uint *>((*bucket)[3]);
    EXPECT_GE(json_num_distinct->value(), 1ULL);

    /*
      Index 1 should be lower inclusive value, and index 2 should be upper
      inclusive value.
    */
    Json_opaque *json_opaque_lower = down_cast<Json_opaque *>((*bucket)[0]);
    Json_opaque *json_opaque_upper = down_cast<Json_opaque *>((*bucket)[1]);

    String current_lower_value(json_opaque_lower->value(),
                               json_opaque_lower->size(), charset);
    String current_upper_value(json_opaque_upper->value(),
                               json_opaque_upper->size(), charset);

    if (i > 0) {
      EXPECT_TRUE(
          Histogram_comparator()(previous_upper_value, current_lower_value));
      EXPECT_LT(previous_cumulative_frequency, current_cumulative_frequency);
    }

    EXPECT_FALSE(
        Histogram_comparator()(current_upper_value, current_lower_value));

    previous_upper_value = current_upper_value;
    previous_cumulative_frequency = current_cumulative_frequency;
  }
}

void VerifyEquiHeightBucketConstraintsDecimal(Histogram *histogram) {
  ASSERT_TRUE(histogram != nullptr);

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *buckets = down_cast<Json_array *>(buckets_dom);

  const my_decimal *previous_upper_value = nullptr;
  double previous_cumulative_frequency = 0.0;
  for (size_t i = 0; i < buckets->size(); ++i) {
    Json_dom *bucket_dom = (*buckets)[i];
    Json_array *bucket = static_cast<Json_array *>(bucket_dom);

    Json_double *json_frequency = down_cast<Json_double *>((*bucket)[2]);
    double current_cumulative_frequency = json_frequency->value();
    EXPECT_GT(current_cumulative_frequency, 0.0);
    EXPECT_LE(current_cumulative_frequency, 1.0);

    Json_uint *json_num_distinct = down_cast<Json_uint *>((*bucket)[3]);
    EXPECT_GE(json_num_distinct->value(), 1ULL);

    /*
      Index 1 should be lower inclusive value, and index 2 should be upper
      inclusive value.
    */
    Json_decimal *json_decimal_lower = down_cast<Json_decimal *>((*bucket)[0]);
    Json_decimal *json_decimal_upper = down_cast<Json_decimal *>((*bucket)[1]);

    const my_decimal *current_lower_value(json_decimal_lower->value());
    const my_decimal *current_upper_value(json_decimal_upper->value());

    if (i > 0) {
      EXPECT_TRUE(
          Histogram_comparator()(*previous_upper_value, *current_lower_value));
      EXPECT_LT(previous_cumulative_frequency, current_cumulative_frequency);
    }

    EXPECT_FALSE(
        Histogram_comparator()(*current_upper_value, *current_lower_value));

    previous_upper_value = current_upper_value;
    previous_cumulative_frequency = current_cumulative_frequency;
  }
}

void VerifyEquiHeightBucketConstraintsTemporal(Histogram *histogram) {
  ASSERT_TRUE(histogram != nullptr);

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *buckets = down_cast<Json_array *>(buckets_dom);

  const MYSQL_TIME *previous_upper_value = nullptr;
  double previous_cumulative_frequency = 0.0;
  for (size_t i = 0; i < buckets->size(); ++i) {
    Json_dom *bucket_dom = (*buckets)[i];
    Json_array *bucket = static_cast<Json_array *>(bucket_dom);

    Json_double *json_frequency = down_cast<Json_double *>((*bucket)[2]);
    double current_cumulative_frequency = json_frequency->value();
    EXPECT_GT(current_cumulative_frequency, 0.0);
    EXPECT_LE(current_cumulative_frequency, 1.0);

    Json_uint *json_num_distinct = down_cast<Json_uint *>((*bucket)[3]);
    EXPECT_GE(json_num_distinct->value(), 1ULL);

    /*
      Index 1 should be lower inclusive value, and index 2 should be upper
      inclusive value.
    */
    Json_datetime *json_datetime_lower =
        down_cast<Json_datetime *>((*bucket)[0]);
    Json_datetime *json_datetime_upper =
        down_cast<Json_datetime *>((*bucket)[1]);

    const MYSQL_TIME *current_lower_value(json_datetime_lower->value());
    const MYSQL_TIME *current_upper_value(json_datetime_upper->value());

    if (i > 0) {
      EXPECT_TRUE(
          Histogram_comparator()(*previous_upper_value, *current_lower_value));
      EXPECT_LT(previous_cumulative_frequency, current_cumulative_frequency);
    }

    EXPECT_FALSE(
        Histogram_comparator()(*current_upper_value, *current_lower_value));

    previous_upper_value = current_upper_value;
    previous_cumulative_frequency = current_cumulative_frequency;
  }
}

/*
  Utility function that verify the following properties for an equi-height
  histogram that is converted to JSON:
    - The histogram has all the "common" JSON fields
      (see VerifyCommonJSONFields).
    - All equi-height buckets have the following types in each index:
      0: J_DOUBLE
      1: Depends on the data type stored in the histogram
      2: Depends on the data type stored in the histogram
      3: J_UINT

  The function does not check that the values are correct, but rather that they
  are present with the expected type.
*/
void VerifyEquiHeightJSONStructure(Histogram *histogram,
                                   enum_json_type expected_json_type) {
  ASSERT_TRUE(histogram != nullptr);

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));
  VerifyCommonJSONFields(&json_object, histogram);

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *buckets = static_cast<Json_array *>(buckets_dom);

  // Verify that all the buckets have the expected structure.
  for (size_t i = 0; i < buckets->size(); ++i) {
    Json_dom *bucket_dom = (*buckets)[i];
    EXPECT_EQ(bucket_dom->json_type(), enum_json_type::J_ARRAY);

    Json_array *bucket = static_cast<Json_array *>(bucket_dom);
    EXPECT_EQ(bucket->size(), 4U);

    // Index 0 should be lower inclusive value.
    EXPECT_EQ((*bucket)[0]->json_type(), expected_json_type);

    // Index 1 should be upper inclusive value.
    EXPECT_EQ((*bucket)[1]->json_type(), expected_json_type);

    // Index 2 should be cumulative frequency.
    EXPECT_EQ((*bucket)[2]->json_type(), enum_json_type::J_DOUBLE);

    // Index 3 should be numer of distinct values.
    EXPECT_EQ((*bucket)[3]->json_type(), enum_json_type::J_UINT);
  }
}

/*
  Utility function that verify the following properties for a singleton
  histogram that is converted to JSON:
    - The histogram has all the "common" JSON fields
      (see VerifyCommonJSONFields).
    - All equi-height buckets have the following types in each index:
      0: J_DOUBLE
      1: Depends on the data type stored in the histogram

  The function does not check that the values are correct, but rather that they
  are present with the expected type.
*/
void VerifySingletonJSONStructure(Histogram *histogram,
                                  enum_json_type expected_json_type) {
  ASSERT_TRUE(histogram != nullptr);

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));
  VerifyCommonJSONFields(&json_object, histogram);

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *buckets = static_cast<Json_array *>(buckets_dom);

  // Verify that all the buckets have the expected structure.
  for (size_t i = 0; i < buckets->size(); ++i) {
    Json_dom *bucket_dom = (*buckets)[i];
    EXPECT_EQ(bucket_dom->json_type(), enum_json_type::J_ARRAY);

    Json_array *bucket = static_cast<Json_array *>(bucket_dom);
    EXPECT_EQ(bucket->size(), 2U);

    // Index 0 should be the value.
    EXPECT_EQ((*bucket)[0]->json_type(), expected_json_type);

    // Index 1 should be cumulative frequency.
    EXPECT_EQ((*bucket)[1]->json_type(), enum_json_type::J_DOUBLE);
  }
}

/*
  Check that a singleton histogram can be built and converted to JSON for all
  supported data types:

    - Double
    - String
    - Uint
    - Int
    - Decimal
    - Datetime (MYSQL_TIME)
    - Date (MYSQL_TIME)
    - Time (MYSQL_TIME)
    - Blob/binary
*/
TEST_F(HistogramsTest, DoubleSingletonToJSON) {
  Singleton<double> *histogram = Singleton<double>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::DOUBLE);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(double_values, double_values.size()));
  EXPECT_EQ(double_values.size(), histogram->get_num_buckets());
  EXPECT_EQ(double_values.size(), histogram->get_num_distinct_values());

  VerifySingletonJSONStructure(histogram, enum_json_type::J_DOUBLE);
  VerifySingletonBucketConstraintsDouble(histogram);
}

TEST_F(HistogramsTest, StringSingletonToJSON) {
  Singleton<String> *histogram = Singleton<String>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::STRING);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(string_values, string_values.size()));
  EXPECT_EQ(string_values.size(), histogram->get_num_buckets());
  EXPECT_EQ(string_values.size(), histogram->get_num_distinct_values());

  VerifySingletonJSONStructure(histogram, enum_json_type::J_OPAQUE);
  VerifySingletonBucketConstraintsString(histogram, &my_charset_latin1);
}

TEST_F(HistogramsTest, UintSingletonToJSON) {
  Singleton<ulonglong> *histogram = Singleton<ulonglong>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::UINT);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(uint_values, uint_values.size()));
  EXPECT_EQ(uint_values.size(), histogram->get_num_buckets());
  EXPECT_EQ(uint_values.size(), histogram->get_num_distinct_values());

  VerifySingletonJSONStructure(histogram, enum_json_type::J_UINT);
  VerifySingletonBucketConstraintsUInt(histogram);
}

TEST_F(HistogramsTest, IntSingletonToJSON) {
  Singleton<longlong> *histogram = Singleton<longlong>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::INT);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(int_values, int_values.size()));
  EXPECT_EQ(int_values.size(), histogram->get_num_buckets());
  EXPECT_EQ(int_values.size(), histogram->get_num_distinct_values());

  VerifySingletonJSONStructure(histogram, enum_json_type::J_INT);
  VerifySingletonBucketConstraintsInt(histogram);
}

TEST_F(HistogramsTest, DecimalSingletonToJSON) {
  Singleton<my_decimal> *histogram = Singleton<my_decimal>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::DECIMAL);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(
      histogram->build_histogram(decimal_values, decimal_values.size()));
  EXPECT_EQ(decimal_values.size(), histogram->get_num_buckets());
  EXPECT_EQ(decimal_values.size(), histogram->get_num_distinct_values());

  VerifySingletonJSONStructure(histogram, enum_json_type::J_DECIMAL);
  VerifySingletonBucketConstraintsDecimal(histogram);
}

TEST_F(HistogramsTest, DatetimeSingletonToJSON) {
  Singleton<MYSQL_TIME> *histogram = Singleton<MYSQL_TIME>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::DATETIME);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(
      histogram->build_histogram(datetime_values, datetime_values.size()));
  EXPECT_EQ(datetime_values.size(), histogram->get_num_buckets());
  EXPECT_EQ(datetime_values.size(), histogram->get_num_distinct_values());

  VerifySingletonJSONStructure(histogram, enum_json_type::J_DATETIME);
  VerifySingletonBucketConstraintsTemporal(histogram);
}

TEST_F(HistogramsTest, DateSingletonToJSON) {
  Singleton<MYSQL_TIME> *histogram = Singleton<MYSQL_TIME>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::DATE);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(date_values, date_values.size()));
  EXPECT_EQ(date_values.size(), histogram->get_num_buckets());
  EXPECT_EQ(date_values.size(), histogram->get_num_distinct_values());

  VerifySingletonJSONStructure(histogram, enum_json_type::J_DATE);
  VerifySingletonBucketConstraintsTemporal(histogram);
}

TEST_F(HistogramsTest, TimeSingletonToJSON) {
  Singleton<MYSQL_TIME> *histogram = Singleton<MYSQL_TIME>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::TIME);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(time_values, time_values.size()));
  EXPECT_EQ(time_values.size(), histogram->get_num_buckets());
  EXPECT_EQ(time_values.size(), histogram->get_num_distinct_values());

  VerifySingletonJSONStructure(histogram, enum_json_type::J_TIME);
  VerifySingletonBucketConstraintsTemporal(histogram);
}

/*
  Check that an equi-height histogram can be built and converted to JSON for all
  supported data types:

    - Double
    - String
    - Uint
    - Int
    - Decimal
    - Datetime (MYSQL_TIME)
    - Date (MYSQL_TIME)
    - Time (MYSQL_TIME)
    - Blob/binary

  Create equi-height histograms with the same number of buckets as the number
  of distinct values in the data set. This will lead to every histogram bucket
  having lower_inclusive_value == upper_inclusive value.

  We check that the resulting JSON has the expected structure, as well as every
  bucket having lower_inclusive_value <= upper_inclusive.
*/
TEST_F(HistogramsTest, DoubleEquiHeightToJSON) {
  Equi_height<double> *histogram = Equi_height<double>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::DOUBLE);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(double_values, double_values.size()));
  EXPECT_EQ(double_values.size(), histogram->get_num_buckets());
  EXPECT_EQ(double_values.size(), histogram->get_num_distinct_values());

  VerifyEquiHeightJSONStructure(histogram, enum_json_type::J_DOUBLE);
  VerifyEquiHeightBucketConstraintsDouble(histogram);
}

TEST_F(HistogramsTest, StringEquiHeightToJSON) {
  Equi_height<String> *histogram = Equi_height<String>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::STRING);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(string_values, string_values.size()));
  EXPECT_EQ(string_values.size(), histogram->get_num_buckets());
  EXPECT_EQ(string_values.size(), histogram->get_num_distinct_values());

  VerifyEquiHeightJSONStructure(histogram, enum_json_type::J_OPAQUE);
  VerifyEquiHeightBucketConstraintsString(histogram, &my_charset_latin1);
}

TEST_F(HistogramsTest, UintEquiHeightToJSON) {
  Equi_height<ulonglong> *histogram = Equi_height<ulonglong>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::UINT);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(uint_values, uint_values.size()));
  EXPECT_EQ(uint_values.size(), histogram->get_num_buckets());
  EXPECT_EQ(uint_values.size(), histogram->get_num_distinct_values());

  VerifyEquiHeightJSONStructure(histogram, enum_json_type::J_UINT);
  VerifyEquiHeightBucketConstraintsUInt(histogram);
}

TEST_F(HistogramsTest, IntEquiHeightToJSON) {
  Equi_height<longlong> *histogram = Equi_height<longlong>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::INT);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(int_values, int_values.size()));
  EXPECT_EQ(int_values.size(), histogram->get_num_buckets());
  EXPECT_EQ(int_values.size(), histogram->get_num_distinct_values());

  VerifyEquiHeightJSONStructure(histogram, enum_json_type::J_INT);
  VerifyEquiHeightBucketConstraintsInt(histogram);
}

TEST_F(HistogramsTest, DecimalEquiHeightToJSON) {
  Equi_height<my_decimal> *histogram = Equi_height<my_decimal>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::DECIMAL);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(
      histogram->build_histogram(decimal_values, decimal_values.size()));
  EXPECT_EQ(decimal_values.size(), histogram->get_num_buckets());
  EXPECT_EQ(decimal_values.size(), histogram->get_num_distinct_values());

  VerifyEquiHeightJSONStructure(histogram, enum_json_type::J_DECIMAL);
  VerifyEquiHeightBucketConstraintsDecimal(histogram);
}

TEST_F(HistogramsTest, DatetimeEquiHeightToJSON) {
  Equi_height<MYSQL_TIME> *histogram = Equi_height<MYSQL_TIME>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::DATETIME);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(
      histogram->build_histogram(datetime_values, datetime_values.size()));
  EXPECT_EQ(datetime_values.size(), histogram->get_num_buckets());
  EXPECT_EQ(datetime_values.size(), histogram->get_num_distinct_values());

  VerifyEquiHeightJSONStructure(histogram, enum_json_type::J_DATETIME);
  VerifyEquiHeightBucketConstraintsTemporal(histogram);
}

TEST_F(HistogramsTest, DateEquiHeightToJSON) {
  Equi_height<MYSQL_TIME> *histogram = Equi_height<MYSQL_TIME>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::DATE);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(date_values, date_values.size()));
  EXPECT_EQ(date_values.size(), histogram->get_num_buckets());
  EXPECT_EQ(date_values.size(), histogram->get_num_distinct_values());

  VerifyEquiHeightJSONStructure(histogram, enum_json_type::J_DATE);
  VerifyEquiHeightBucketConstraintsTemporal(histogram);
}

TEST_F(HistogramsTest, TimeEquiHeightToJSON) {
  Equi_height<MYSQL_TIME> *histogram = Equi_height<MYSQL_TIME>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::TIME);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(time_values, time_values.size()));
  EXPECT_EQ(time_values.size(), histogram->get_num_buckets());
  EXPECT_EQ(time_values.size(), histogram->get_num_distinct_values());

  VerifyEquiHeightJSONStructure(histogram, enum_json_type::J_TIME);
  VerifyEquiHeightBucketConstraintsTemporal(histogram);
}

/*
  Create Equi-height histograms with fewer buckets than the distinct number
  of values. This will force at least one of the buckets to have
  lower_inclusive_value != upper_inclusive_value.

  We check that the resulting JSON has the expected structure, as well as every
  bucket having lower_inclusive_value <= upper_inclusive.
*/
TEST_F(HistogramsTest, DoubleEquiHeightFewBuckets) {
  Equi_height<double> *histogram = Equi_height<double>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::DOUBLE);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(double_values, 2U));
  VerifyEquiHeightJSONStructure(histogram, enum_json_type::J_DOUBLE);
  VerifyEquiHeightBucketConstraintsDouble(histogram);
}

TEST_F(HistogramsTest, StringEquiHeightFewBuckets) {
  Equi_height<String> *histogram = Equi_height<String>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::STRING);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(string_values, 2U));
  VerifyEquiHeightJSONStructure(histogram, enum_json_type::J_OPAQUE);
  VerifyEquiHeightBucketConstraintsString(histogram, &my_charset_latin1);
}

TEST_F(HistogramsTest, UintEquiHeightFewBuckets) {
  Equi_height<ulonglong> *histogram = Equi_height<ulonglong>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::UINT);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(uint_values, 2U));
  VerifyEquiHeightJSONStructure(histogram, enum_json_type::J_UINT);
  VerifyEquiHeightBucketConstraintsUInt(histogram);
}

TEST_F(HistogramsTest, IntEquiHeightFewBuckets) {
  Equi_height<longlong> *histogram = Equi_height<longlong>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::INT);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(int_values, 2U));
  VerifyEquiHeightJSONStructure(histogram, enum_json_type::J_INT);
  VerifyEquiHeightBucketConstraintsInt(histogram);
}

TEST_F(HistogramsTest, DecimalEquiHeightFewBuckets) {
  Equi_height<my_decimal> *histogram = Equi_height<my_decimal>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::DECIMAL);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(decimal_values, 2U));
  VerifyEquiHeightJSONStructure(histogram, enum_json_type::J_DECIMAL);
  VerifyEquiHeightBucketConstraintsDecimal(histogram);
}

TEST_F(HistogramsTest, DatetimeEquiHeightFewBuckets) {
  Equi_height<MYSQL_TIME> *histogram = Equi_height<MYSQL_TIME>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::DATETIME);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(datetime_values, 2U));
  VerifyEquiHeightJSONStructure(histogram, enum_json_type::J_DATETIME);
  VerifyEquiHeightBucketConstraintsTemporal(histogram);
}

TEST_F(HistogramsTest, DateEquiHeightFewBuckets) {
  Equi_height<MYSQL_TIME> *histogram = Equi_height<MYSQL_TIME>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::DATE);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(date_values, 2U));
  VerifyEquiHeightJSONStructure(histogram, enum_json_type::J_DATE);
  VerifyEquiHeightBucketConstraintsTemporal(histogram);
}

TEST_F(HistogramsTest, TimeEquiHeightFewBuckets) {
  Equi_height<MYSQL_TIME> *histogram = Equi_height<MYSQL_TIME>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::TIME);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_FALSE(histogram->build_histogram(time_values, 2U));
  VerifyEquiHeightJSONStructure(histogram, enum_json_type::J_TIME);
  VerifyEquiHeightBucketConstraintsTemporal(histogram);
}

/*
  Verify that the "auto-select histogram"-mechanism works as expected. That is,
  it should select a singleton histogram when we have less or equal amount of
  distinct values as the specified amount of buckets. In all other cases it
  should create an equi-height histogram.
*/
TEST_F(HistogramsTest, AutoSelectHistogramType) {
  /*
    Case 1: Less buckets than the number of distinct values. We should end up
    with an equi-height histogram.
  */
  size_t num_buckets = double_values.size() - 1;
  Histogram *histogram1 = build_histogram(&m_mem_root, double_values,
                                          num_buckets, "db1", "tbl1", "col1");

  EXPECT_EQ(Histogram::enum_histogram_type::EQUI_HEIGHT,
            histogram1->get_histogram_type());
  EXPECT_LE(histogram1->get_num_buckets(), num_buckets);
  EXPECT_EQ(histogram1->get_num_distinct_values(), double_values.size());

  /*
    Case 2: Same number of buckets as the number of distinct values. We should
    end up with a singleton histogram.
  */
  num_buckets = double_values.size();
  Histogram *histogram2 = build_histogram(&m_mem_root, double_values,
                                          num_buckets, "db1", "tbl1", "col1");

  EXPECT_EQ(Histogram::enum_histogram_type::SINGLETON,
            histogram2->get_histogram_type());
  EXPECT_EQ(histogram2->get_num_buckets(), double_values.size());
  EXPECT_EQ(histogram2->get_num_distinct_values(), double_values.size());

  /*
    Case 3: More buckets than the number of distinct values. We should end up
    with a singleton histogram.
  */
  num_buckets = std::numeric_limits<std::size_t>::max();
  Histogram *histogram3 = build_histogram(&m_mem_root, double_values,
                                          num_buckets, "db1", "tbl1", "col1");

  EXPECT_EQ(Histogram::enum_histogram_type::SINGLETON,
            histogram3->get_histogram_type());
  EXPECT_LE(histogram3->get_num_buckets(), double_values.size());
  EXPECT_EQ(histogram3->get_num_distinct_values(), double_values.size());
}

/*
  An utility function that verifies the actual values in the singleton JSON
  bucket.
*/
void VerifySingletonBucketContentsInt(Json_array *singleton_buckets,
                                      int bucket_index,
                                      double cumulative_frequency,
                                      longlong value) {
  Json_array *json_bucket =
      down_cast<Json_array *>((*singleton_buckets)[bucket_index]);

  Json_int *json_value = down_cast<Json_int *>((*json_bucket)[0]);
  Json_double *json_cumulative_frequency =
      down_cast<Json_double *>((*json_bucket)[1]);

  EXPECT_DOUBLE_EQ(cumulative_frequency, json_cumulative_frequency->value());
  EXPECT_EQ(value, json_value->value());
}

/*
  An utility function that verifies the actual values in the singleton JSON
  bucket.
*/
void VerifySingletonBucketContentsUInt(Json_array *singleton_buckets,
                                       int bucket_index,
                                       double cumulative_frequency,
                                       ulonglong value) {
  Json_array *json_bucket =
      down_cast<Json_array *>((*singleton_buckets)[bucket_index]);

  Json_uint *json_value = down_cast<Json_uint *>((*json_bucket)[0]);
  Json_double *json_cumulative_frequency =
      down_cast<Json_double *>((*json_bucket)[1]);

  EXPECT_DOUBLE_EQ(cumulative_frequency, json_cumulative_frequency->value());
  EXPECT_EQ(value, json_value->value());
}

/*
  An utility function that verifies the actual values in the singleton JSON
  bucket.
*/
void VerifySingletonBucketContentsString(Json_array *singleton_buckets,
                                         int bucket_index,
                                         double cumulative_frequency,
                                         String value,
                                         const CHARSET_INFO *charset) {
  Json_array *json_bucket =
      down_cast<Json_array *>((*singleton_buckets)[bucket_index]);

  Json_opaque *json_value_dom = down_cast<Json_opaque *>((*json_bucket)[0]);
  Json_double *json_cumulative_frequency =
      down_cast<Json_double *>((*json_bucket)[1]);

  String json_value(json_value_dom->value(), json_value_dom->size(), charset);

  EXPECT_EQ(json_value.charset()->number, value.charset()->number);
  EXPECT_DOUBLE_EQ(cumulative_frequency, json_cumulative_frequency->value());
  EXPECT_EQ(sortcmp(&value, &json_value, charset), 0);
}

/*
  An utility function that verifies the actual values in the singleton JSON
  bucket.
*/
void VerifySingletonBucketContentsDouble(Json_array *singleton_buckets,
                                         int bucket_index,
                                         double cumulative_frequency,
                                         double value) {
  Json_array *json_bucket =
      down_cast<Json_array *>((*singleton_buckets)[bucket_index]);

  Json_double *json_value = down_cast<Json_double *>((*json_bucket)[0]);
  Json_double *json_cumulative_frequency =
      down_cast<Json_double *>((*json_bucket)[1]);

  EXPECT_DOUBLE_EQ(cumulative_frequency, json_cumulative_frequency->value());
  EXPECT_EQ(value, json_value->value());
}

/*
  An utility function that verifies the actual values in the singleton JSON
  bucket.
*/
void VerifySingletonBucketContentsDecimal(Json_array *singleton_buckets,
                                          int bucket_index,
                                          double cumulative_frequency,
                                          my_decimal value) {
  Json_array *json_bucket =
      down_cast<Json_array *>((*singleton_buckets)[bucket_index]);

  Json_decimal *json_value = down_cast<Json_decimal *>((*json_bucket)[0]);
  Json_double *json_cumulative_frequency =
      down_cast<Json_double *>((*json_bucket)[1]);

  EXPECT_DOUBLE_EQ(cumulative_frequency, json_cumulative_frequency->value());
  EXPECT_EQ(my_decimal_cmp(json_value->value(), &value), 0);
}

/*
  An utility function that verifies the actual values in the singleton JSON
  bucket.
*/
void VerifySingletonBucketContentsTemporal(Json_array *singleton_buckets,
                                           int bucket_index,
                                           double cumulative_frequency,
                                           MYSQL_TIME value) {
  Json_array *json_bucket =
      down_cast<Json_array *>((*singleton_buckets)[bucket_index]);

  Json_datetime *json_value = down_cast<Json_datetime *>((*json_bucket)[0]);
  Json_double *json_cumulative_frequency =
      down_cast<Json_double *>((*json_bucket)[1]);

  EXPECT_DOUBLE_EQ(cumulative_frequency, json_cumulative_frequency->value());
  EXPECT_EQ(my_time_compare(*json_value->value(), value), 0);
}

template <typename T>
Equi_height<T> *BuildEquiHeightAndVerifyBasicProperties(
    MEM_ROOT *mem_root, const Value_map<T> &value_map, size_t num_buckets) {
  Equi_height<T> *histogram = Equi_height<T>::create(
      mem_root, "db1", "tbl1", "col1", value_map.get_data_type());
  EXPECT_TRUE(histogram != nullptr);

  EXPECT_EQ(histogram->get_num_buckets(), 0U);
  EXPECT_EQ(histogram->get_num_buckets_specified(), 0U);
  EXPECT_EQ(histogram->get_num_distinct_values(), 0U);
  EXPECT_EQ(histogram->get_data_type(), value_map.get_data_type());

  EXPECT_STREQ(histogram->get_database_name().str, "db1");
  EXPECT_STREQ(histogram->get_table_name().str, "tbl1");
  EXPECT_STREQ(histogram->get_column_name().str, "col1");

  EXPECT_FALSE(histogram->build_histogram(value_map, num_buckets));
  EXPECT_EQ(histogram->get_num_buckets(), num_buckets);
  EXPECT_EQ(histogram->get_num_buckets_specified(), num_buckets);
  EXPECT_EQ(histogram->get_num_distinct_values(), value_map.size());
  EXPECT_EQ(histogram->get_character_set()->number,
            value_map.get_character_set()->number);

  return histogram;
}

template <typename T>
void EquiHeightBucketsAreEqual(const equi_height::Bucket<T> &b1,
                               const equi_height::Bucket<T> &b2) {
  EXPECT_EQ(b1.get_cumulative_frequency(), b2.get_cumulative_frequency());
  EXPECT_EQ(b1.get_num_distinct(), b2.get_num_distinct());

  // Equality check: Neither value is less than the other.
  EXPECT_FALSE(Histogram_comparator()(b1.get_lower_inclusive(),
                                      b2.get_lower_inclusive()));
  EXPECT_FALSE(Histogram_comparator()(b2.get_lower_inclusive(),
                                      b1.get_lower_inclusive()));

  EXPECT_FALSE(Histogram_comparator()(b1.get_upper_inclusive(),
                                      b2.get_upper_inclusive()));
  EXPECT_FALSE(Histogram_comparator()(b2.get_upper_inclusive(),
                                      b1.get_upper_inclusive()));
}

template <typename T>
void EquiHeightHistogramsAreEqual(const Equi_height<T> *h1,
                                  const Equi_height<T> *h2) {
  EXPECT_STREQ(h1->get_database_name().str, h2->get_database_name().str);
  EXPECT_STREQ(h1->get_table_name().str, h2->get_table_name().str);
  EXPECT_STREQ(h1->get_column_name().str, h2->get_column_name().str);

  EXPECT_EQ(h1->get_histogram_type(), h2->get_histogram_type());
  EXPECT_EQ(h1->get_data_type(), h2->get_data_type());
  EXPECT_EQ(h1->get_num_buckets(), h2->get_num_buckets());
  EXPECT_EQ(h1->get_num_buckets_specified(), h2->get_num_buckets_specified());
  EXPECT_EQ(h1->get_num_distinct_values(), h2->get_num_distinct_values());
  EXPECT_EQ(h1->get_non_null_values_fraction(),
            h2->get_non_null_values_fraction());
  EXPECT_EQ(h1->get_null_values_fraction(), h2->get_null_values_fraction());
  EXPECT_EQ(h1->get_character_set()->number, h2->get_character_set()->number);
  EXPECT_EQ(h1->get_sampling_rate(), h2->get_sampling_rate());

  ASSERT_EQ(h1->get_num_buckets(), h2->get_num_buckets());
  for (size_t i = 0; i < h1->get_num_buckets(); ++i) {
    EquiHeightBucketsAreEqual(h1->get_buckets()[i], h2->get_buckets()[i]);
  }
}

/*
  Serialize and deserialize the given histogram.
  Verify that the deserialized histogram matches the original.
*/
template <typename T>
void VerifyEquiHeightSerialization(MEM_ROOT *mem_root,
                                   const Equi_height<T> *histogram) {
  // Serialization.
  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  // Deserialization.
  Error_context ctx;
  Histogram *deserialized_histogram = Histogram::json_to_histogram(
      mem_root, "db1", "tbl1", "col1", json_object, &ctx);
  ASSERT_TRUE(deserialized_histogram != nullptr);
  Equi_height<T> *deserialized_equi_height =
      dynamic_cast<Equi_height<T> *>(deserialized_histogram);
  ASSERT_TRUE(deserialized_equi_height != nullptr);

  EquiHeightHistogramsAreEqual(histogram, deserialized_equi_height);
}

/*
  Verify that histogram selectivity estimates for the values in the value_map
  are within max_abs_error of the actual selectivities.
*/
template <typename T>
void VerifyEquiHeightSelectivities(const Value_map<T> &value_map,
                                   const Equi_height<T> *histogram,
                                   double max_error_factor) {
  double max_abs_error =
      max_error_factor /
      static_cast<double>(histogram->get_num_buckets_specified());

  ha_rows non_null_values = 0;
  for (const auto &[value, count] : value_map) non_null_values += count;
  ha_rows total_values = non_null_values + value_map.get_num_null_values();

  ha_rows cumulative_values = 0;
  for (const auto &[value, count] : value_map) {
    double less_than_selectivity =
        static_cast<double>(cumulative_values) / total_values;
    EXPECT_NEAR(less_than_selectivity,
                histogram->get_less_than_selectivity(value), max_abs_error);

    double equal_to_selectivity = static_cast<double>(count) / total_values;
    EXPECT_NEAR(equal_to_selectivity,
                histogram->get_equal_to_selectivity(value), max_abs_error);

    double greater_than_selectivity =
        1.0 - (less_than_selectivity + equal_to_selectivity);
    EXPECT_NEAR(greater_than_selectivity,
                histogram->get_greater_than_selectivity(value), max_abs_error);

    cumulative_values += count;
  }

  double null_fraction =
      static_cast<double>(value_map.get_num_null_values()) / total_values;
  double non_null_fraction =
      static_cast<double>(non_null_values) / total_values;

  const double null_fraction_max_error = 1.0e-9;
  EXPECT_NEAR(histogram->get_null_values_fraction(), null_fraction,
              null_fraction_max_error);
  EXPECT_NEAR(histogram->get_non_null_values_fraction(), non_null_fraction,
              null_fraction_max_error);
}

/*
  The json type that we expect histogram values (bucket endpoints) of a given
  type to be serialized into.
*/
enum_json_type ValueMapTypeToJsonType(Value_map_type value_type) {
  switch (value_type) {
    case Value_map_type::INVALID:
      return enum_json_type::J_ERROR;
    case Value_map_type::STRING:
      return enum_json_type::J_OPAQUE;
    case Value_map_type::INT:
      return enum_json_type::J_INT;
    case Value_map_type::UINT:
      return enum_json_type::J_UINT;
    case Value_map_type::DOUBLE:
      return enum_json_type::J_DOUBLE;
    case Value_map_type::DECIMAL:
      return enum_json_type::J_DECIMAL;
    case Value_map_type::DATE:
      return enum_json_type::J_DATE;
    case Value_map_type::TIME:
      return enum_json_type::J_TIME;
    case Value_map_type::DATETIME:
      return enum_json_type::J_DATETIME;
    case Value_map_type::ENUM:
      return enum_json_type::J_UINT;
    case Value_map_type::SET:
      return enum_json_type::J_UINT;
  }
  return enum_json_type::J_ERROR;
}

template <typename T>
void VerifyEquiHeight(MEM_ROOT *mem_root, const Value_map<T> &value_map,
                      size_t num_buckets, double max_error_factor = 1.0) {
  Equi_height<T> *histogram =
      BuildEquiHeightAndVerifyBasicProperties(mem_root, value_map, num_buckets);
  enum_json_type expected_json_value_type =
      ValueMapTypeToJsonType(histogram->get_data_type());
  VerifyEquiHeightJSONStructure(histogram, expected_json_value_type);
  VerifyEquiHeightSerialization(mem_root, histogram);
  VerifyEquiHeightSelectivities(value_map, histogram, max_error_factor);
}

TEST_F(HistogramsTest, VerifyEquiHeightContentsInt1) {
  size_t num_buckets = 3;
  double max_error_factor = 1.0;
  VerifyEquiHeight(&m_mem_root, int_values, num_buckets, max_error_factor);
}

TEST_F(HistogramsTest, VerifyEquiHeightContentsInt2) {
  /*
    Create a value map with the following key/value pairs;
      [NULL, 10000]
      [0,    10000]
      [1,     9999]
      [2,     9998]
      ...
      [9998,     2]
      [9999,     1]
  */
  Value_map<longlong> values(&my_charset_numeric, Value_map_type::INT);
  values.add_null_values(10000);
  for (longlong i = 0; i < 10000; i++) {
    size_t frequency = static_cast<size_t>(10000 - i);
    values.add_values(i, frequency);
  }

  size_t num_buckets = 10;
  double max_error_factor = 1.0;
  VerifyEquiHeight(&m_mem_root, values, num_buckets, max_error_factor);
}

TEST_F(HistogramsTest, VerifyEquiHeightContentsDouble) {
  size_t num_buckets = 3;
  double max_error_factor = 1.0;
  VerifyEquiHeight(&m_mem_root, double_values, num_buckets, max_error_factor);
}

TEST_F(HistogramsTest, VerifyEquiHeightContentsString) {
  size_t num_buckets = 3;
  double max_error_factor = 1.0;
  VerifyEquiHeight(&m_mem_root, string_values, num_buckets, max_error_factor);
}

TEST_F(HistogramsTest, VerifyEquiHeightContentsUint) {
  size_t num_buckets = 3;
  double max_error_factor = 1.0;
  VerifyEquiHeight(&m_mem_root, uint_values, num_buckets, max_error_factor);
}

TEST_F(HistogramsTest, VerifyEquiHeightContentsDecimal) {
  size_t num_buckets = 3;
  double max_error_factor = 1.0;
  VerifyEquiHeight(&m_mem_root, decimal_values, num_buckets, max_error_factor);
}

TEST_F(HistogramsTest, VerifyEquiHeightContentsDatetime) {
  size_t num_buckets = 3;
  double max_error_factor = 1.0;
  VerifyEquiHeight(&m_mem_root, datetime_values, num_buckets, max_error_factor);
}

TEST_F(HistogramsTest, VerifyEquiHeightContentsBlob) {
  size_t num_buckets = 3;
  double max_error_factor = 1.0;
  VerifyEquiHeight(&m_mem_root, blob_values, num_buckets, max_error_factor);
}

/*
  Create a singleton histogram, where we manually verify the value for every
  property in every bucket.
*/
TEST_F(HistogramsTest, VerifySingletonContentsDouble) {
  Singleton<double> *histogram = Singleton<double>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::DOUBLE);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_STREQ(histogram->get_database_name().str, "db1");
  EXPECT_STREQ(histogram->get_table_name().str, "tbl1");
  EXPECT_STREQ(histogram->get_column_name().str, "col1");

  Value_map<double> value_map(&my_charset_numeric, Value_map_type::DOUBLE);
  value_map.add_null_values(10);
  value_map.insert(double_values.begin(), double_values.end());

  EXPECT_FALSE(histogram->build_histogram(value_map, value_map.size()));
  EXPECT_EQ(histogram->get_num_buckets(), value_map.size());
  EXPECT_EQ(histogram->get_num_distinct_values(), value_map.size());

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *json_buckets = static_cast<Json_array *>(buckets_dom);

  VerifySingletonBucketContentsDouble(json_buckets, 0, (10.0 / 70.0),
                                      std::numeric_limits<double>::lowest());

  VerifySingletonBucketContentsDouble(json_buckets, 1, (20.0 / 70.0), 0.0);

  VerifySingletonBucketContentsDouble(json_buckets, 2, (30.0 / 70.0),
                                      std::numeric_limits<double>::epsilon());

  VerifySingletonBucketContentsDouble(json_buckets, 3, (40.0 / 70.0), 42.0);

  VerifySingletonBucketContentsDouble(json_buckets, 4, (50.0 / 70.0), 43.0);

  VerifySingletonBucketContentsDouble(json_buckets, 5, (60.0 / 70.0),
                                      std::numeric_limits<double>::max());
}

/*
  Create a singleton histogram, where we manually verify the value for every
  property in every bucket.
*/
TEST_F(HistogramsTest, VerifySingletonContentsInt) {
  Singleton<longlong> *histogram = Singleton<longlong>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::INT);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_STREQ(histogram->get_database_name().str, "db1");
  EXPECT_STREQ(histogram->get_table_name().str, "tbl1");
  EXPECT_STREQ(histogram->get_column_name().str, "col1");

  Value_map<longlong> value_map(&my_charset_numeric, Value_map_type::INT);
  value_map.add_null_values(10);
  value_map.insert(int_values.begin(), int_values.end());

  EXPECT_FALSE(histogram->build_histogram(value_map, value_map.size()));
  EXPECT_EQ(histogram->get_num_buckets(), value_map.size());
  EXPECT_EQ(histogram->get_num_distinct_values(), value_map.size());

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *json_buckets = static_cast<Json_array *>(buckets_dom);

  VerifySingletonBucketContentsInt(json_buckets, 0, (10.0 / 80.0),
                                   std::numeric_limits<longlong>::lowest());

  VerifySingletonBucketContentsInt(json_buckets, 1, (20.0 / 80.0), -1LL);

  VerifySingletonBucketContentsInt(json_buckets, 2, (30.0 / 80.0), 0LL);

  VerifySingletonBucketContentsInt(json_buckets, 3, (40.0 / 80.0), 1LL);

  VerifySingletonBucketContentsInt(json_buckets, 4, (50.0 / 80.0), 42LL);

  VerifySingletonBucketContentsInt(json_buckets, 5, (60.0 / 80.0), 10000LL);

  VerifySingletonBucketContentsInt(json_buckets, 6, (70.0 / 80.0),
                                   std::numeric_limits<longlong>::max());
}

/*
  Create a singleton histogram, where we manually verify the value for every
  property in every bucket.
*/
TEST_F(HistogramsTest, VerifySingletonContentsUInt) {
  Singleton<ulonglong> *histogram = Singleton<ulonglong>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::UINT);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_STREQ(histogram->get_database_name().str, "db1");
  EXPECT_STREQ(histogram->get_table_name().str, "tbl1");
  EXPECT_STREQ(histogram->get_column_name().str, "col1");

  Value_map<ulonglong> value_map(&my_charset_numeric, Value_map_type::UINT);
  value_map.add_null_values(10);
  value_map.insert(uint_values.begin(), uint_values.end());

  EXPECT_FALSE(histogram->build_histogram(value_map, value_map.size()));
  EXPECT_EQ(histogram->get_num_buckets(), value_map.size());
  EXPECT_EQ(histogram->get_num_distinct_values(), value_map.size());

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *json_buckets = static_cast<Json_array *>(buckets_dom);

  VerifySingletonBucketContentsUInt(json_buckets, 0, (10.0 / 60.0),
                                    std::numeric_limits<ulonglong>::lowest());

  VerifySingletonBucketContentsUInt(json_buckets, 1, (20.0 / 60.0), 42ULL);

  VerifySingletonBucketContentsUInt(json_buckets, 2, (30.0 / 60.0), 43ULL);

  VerifySingletonBucketContentsUInt(json_buckets, 3, (40.0 / 60.0), 10000ULL);

  VerifySingletonBucketContentsUInt(json_buckets, 4, (50.0 / 60.0),
                                    std::numeric_limits<ulonglong>::max());
}

/*
  Create a singleton histogram, where we manually verify the value for every
  property in every bucket.
*/
TEST_F(HistogramsTest, VerifySingletonContentsString) {
  Singleton<String> *histogram = Singleton<String>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::STRING);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_STREQ(histogram->get_database_name().str, "db1");
  EXPECT_STREQ(histogram->get_table_name().str, "tbl1");
  EXPECT_STREQ(histogram->get_column_name().str, "col1");

  Value_map<String> value_map(&my_charset_latin1, Value_map_type::STRING);
  value_map.add_null_values(10);
  value_map.insert(string_values.begin(), string_values.end());

  EXPECT_FALSE(histogram->build_histogram(value_map, value_map.size()));
  EXPECT_EQ(histogram->get_num_buckets(), value_map.size());
  EXPECT_EQ(histogram->get_num_distinct_values(), value_map.size());

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *json_buckets = static_cast<Json_array *>(buckets_dom);

  String string1("", &my_charset_latin1);
  String string2("string1", &my_charset_latin1);
  String string3("string2", &my_charset_latin1);
  String string4("string3", &my_charset_latin1);
  String string5("string4", &my_charset_latin1);

  VerifySingletonBucketContentsString(json_buckets, 0, (10.0 / 60.0), string1,
                                      &my_charset_latin1);
  VerifySingletonBucketContentsString(json_buckets, 1, (20.0 / 60.0), string2,
                                      &my_charset_latin1);
  VerifySingletonBucketContentsString(json_buckets, 2, (30.0 / 60.0), string3,
                                      &my_charset_latin1);
  VerifySingletonBucketContentsString(json_buckets, 3, (40.0 / 60.0), string4,
                                      &my_charset_latin1);
  VerifySingletonBucketContentsString(json_buckets, 4, (50.0 / 60.0), string5,
                                      &my_charset_latin1);
}

/*
  Create a singleton histogram, where we manually verify the value for every
  property in every bucket.
*/
TEST_F(HistogramsTest, VerifySingletonContentsDecimal) {
  Singleton<my_decimal> *histogram = Singleton<my_decimal>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::DECIMAL);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_STREQ(histogram->get_database_name().str, "db1");
  EXPECT_STREQ(histogram->get_table_name().str, "tbl1");
  EXPECT_STREQ(histogram->get_column_name().str, "col1");

  Value_map<my_decimal> value_map(&my_charset_latin1, Value_map_type::DECIMAL);
  value_map.add_null_values(10);
  value_map.insert(decimal_values.begin(), decimal_values.end());

  EXPECT_FALSE(histogram->build_histogram(value_map, value_map.size()));
  EXPECT_EQ(histogram->get_num_buckets(), value_map.size());
  EXPECT_EQ(histogram->get_num_distinct_values(), value_map.size());

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *json_buckets = static_cast<Json_array *>(buckets_dom);

  my_decimal decimal1;
  int2my_decimal(E_DEC_FATAL_ERROR, -1000LL, false, &decimal1);

  my_decimal decimal2;
  int2my_decimal(E_DEC_FATAL_ERROR, 0LL, false, &decimal2);

  my_decimal decimal3;
  int2my_decimal(E_DEC_FATAL_ERROR, 1LL, false, &decimal3);

  my_decimal decimal4;
  int2my_decimal(E_DEC_FATAL_ERROR, 42LL, false, &decimal4);

  my_decimal decimal5;
  int2my_decimal(E_DEC_FATAL_ERROR, 1000LL, false, &decimal5);

  VerifySingletonBucketContentsDecimal(json_buckets, 0, (10.0 / 60.0),
                                       decimal1);
  VerifySingletonBucketContentsDecimal(json_buckets, 1, (20.0 / 60.0),
                                       decimal2);
  VerifySingletonBucketContentsDecimal(json_buckets, 2, (30.0 / 60.0),
                                       decimal3);
  VerifySingletonBucketContentsDecimal(json_buckets, 3, (40.0 / 60.0),
                                       decimal4);
  VerifySingletonBucketContentsDecimal(json_buckets, 4, (50.0 / 60.0),
                                       decimal5);
}

/*
  Create a singleton histogram, where we manually verify the value for every
  property in every bucket.
*/
TEST_F(HistogramsTest, VerifySingletonContentsDateTime) {
  Singleton<MYSQL_TIME> *histogram = Singleton<MYSQL_TIME>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::DATETIME);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_STREQ(histogram->get_database_name().str, "db1");
  EXPECT_STREQ(histogram->get_table_name().str, "tbl1");
  EXPECT_STREQ(histogram->get_column_name().str, "col1");

  Value_map<MYSQL_TIME> value_map(&my_charset_latin1, Value_map_type::DATETIME);
  value_map.add_null_values(10);
  value_map.insert(datetime_values.begin(), datetime_values.end());

  EXPECT_FALSE(histogram->build_histogram(value_map, value_map.size()));
  EXPECT_EQ(histogram->get_num_buckets(), value_map.size());
  EXPECT_EQ(histogram->get_num_distinct_values(), value_map.size());

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *json_buckets = static_cast<Json_array *>(buckets_dom);

  MYSQL_TIME time1;
  TIME_from_longlong_datetime_packed(&time1, 914866242077065216);

  MYSQL_TIME time2;
  TIME_from_longlong_datetime_packed(&time2, 914866242077065217);

  MYSQL_TIME time3;
  TIME_from_longlong_datetime_packed(&time3, 1845541820734373888);

  MYSQL_TIME time4;
  TIME_from_longlong_datetime_packed(&time4, 9147936188962652734);

  MYSQL_TIME time5;
  TIME_from_longlong_datetime_packed(&time5, 9147936188962652735);

  VerifySingletonBucketContentsTemporal(json_buckets, 0, (10.0 / 60.0), time1);
  VerifySingletonBucketContentsTemporal(json_buckets, 1, (20.0 / 60.0), time2);
  VerifySingletonBucketContentsTemporal(json_buckets, 2, (30.0 / 60.0), time3);
  VerifySingletonBucketContentsTemporal(json_buckets, 3, (40.0 / 60.0), time4);
  VerifySingletonBucketContentsTemporal(json_buckets, 4, (50.0 / 60.0), time5);
}

/*
  Create a singleton histogram, where we manually verify the value for every
  property in every bucket.
*/
TEST_F(HistogramsTest, VerifySingletonContentsBlob) {
  Singleton<String> *histogram = Singleton<String>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::STRING);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_STREQ(histogram->get_database_name().str, "db1");
  EXPECT_STREQ(histogram->get_table_name().str, "tbl1");
  EXPECT_STREQ(histogram->get_column_name().str, "col1");

  Value_map<String> value_map(&my_charset_bin, Value_map_type::STRING);
  value_map.add_null_values(10);
  value_map.insert(blob_values.begin(), blob_values.end());

  EXPECT_FALSE(histogram->build_histogram(value_map, value_map.size()));
  EXPECT_EQ(histogram->get_num_buckets(), value_map.size());
  EXPECT_EQ(histogram->get_num_distinct_values(), value_map.size());

  Json_object json_object;
  EXPECT_FALSE(histogram->histogram_to_json(&json_object));

  Json_dom *buckets_dom = json_object.get("buckets");
  Json_array *json_buckets = static_cast<Json_array *>(buckets_dom);

  String blob1(blob_buf1, 4, &my_charset_bin);
  String blob2("bar", &my_charset_bin);
  String blob3("foo", &my_charset_bin);
  String blob4("foobar", &my_charset_bin);
  String blob5(blob_buf2, 4, &my_charset_bin);

  VerifySingletonBucketContentsString(json_buckets, 0, (10.0 / 60.0), blob1,
                                      &my_charset_bin);
  VerifySingletonBucketContentsString(json_buckets, 1, (20.0 / 60.0), blob2,
                                      &my_charset_bin);
  VerifySingletonBucketContentsString(json_buckets, 2, (30.0 / 60.0), blob3,
                                      &my_charset_bin);
  VerifySingletonBucketContentsString(json_buckets, 3, (40.0 / 60.0), blob4,
                                      &my_charset_bin);
  VerifySingletonBucketContentsString(json_buckets, 4, (50.0 / 60.0), blob5,
                                      &my_charset_bin);
}

/*
  Create an equi-height histogram with zero buckets sepcified. Ensure that the
  resulting histogram actually have zero buckets.
*/
TEST_F(HistogramsTest, EmptyEquiHeightHistogram) {
  Equi_height<longlong> *histogram = Equi_height<longlong>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::INT);
  ASSERT_TRUE(histogram != nullptr);

  Value_map<longlong> empty_value_map(&my_charset_numeric, Value_map_type::INT);

  // Empty map, no null values, but several buckets specified.
  EXPECT_FALSE(histogram->build_histogram(empty_value_map, 10U));
  EXPECT_EQ(histogram->get_num_buckets(), 0U);
  EXPECT_EQ(histogram->get_num_distinct_values(), 0U);

  // Empty map, multiple null values and several buckets specified.
  empty_value_map.add_null_values(500);
  EXPECT_FALSE(histogram->build_histogram(empty_value_map, 10U));
  EXPECT_EQ(histogram->get_num_buckets(), 0U);
  EXPECT_EQ(histogram->get_num_distinct_values(), 0U);
}

/*
  Create a singleton histogram from an empty value map. Ensure that the
  resulting histogram actually have zero buckets.
*/
TEST_F(HistogramsTest, EmptySingletonHistogram) {
  Singleton<longlong> *histogram = Singleton<longlong>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::INT);
  ASSERT_TRUE(histogram != nullptr);

  Value_map<longlong> empty_value_map(&my_charset_numeric, Value_map_type::INT);

  // Empty map, no null values,
  EXPECT_FALSE(histogram->build_histogram(empty_value_map, 10U));
  EXPECT_EQ(histogram->get_num_buckets(), 0U);
  EXPECT_EQ(histogram->get_num_distinct_values(), 0U);
}

/*
  Create an equi-height histogram from an empty value map, but with several NULL
  values. Check that the resulting histogram has a fraction of NULL values equal
  to 1.0.
*/
TEST_F(HistogramsTest, EquiHeightNullValues) {
  Equi_height<longlong> *histogram = Equi_height<longlong>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::INT);
  ASSERT_TRUE(histogram != nullptr);

  Value_map<longlong> empty_value_map(&my_charset_numeric, Value_map_type::INT);
  empty_value_map.add_null_values(10);

  EXPECT_FALSE(histogram->build_histogram(empty_value_map, 1U));
  EXPECT_DOUBLE_EQ(histogram->get_null_values_fraction(), 1.0);
}

/*
  Create a singleton histogram from an empty value map, but with several NULL
  values. Check that the resulting histogram has a fraction of NULL values equal
  to 1.0.
*/
TEST_F(HistogramsTest, SingletonNullValues) {
  Singleton<longlong> *histogram = Singleton<longlong>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::INT);
  ASSERT_TRUE(histogram != nullptr);

  Value_map<longlong> empty_value_map(&my_charset_numeric, Value_map_type::INT);
  empty_value_map.add_null_values(10);

  EXPECT_FALSE(histogram->build_histogram(empty_value_map, 10U));
  EXPECT_DOUBLE_EQ(histogram->get_null_values_fraction(), 1.0);
}

/*
  Check that the histogram comparator only checks the 42 first characters of
  long string values. If the strings differ at any character after the 42nd
  character, the strings should be considered equal.

  This does not test any histogram per se, but the histogram comparator.
*/
TEST_F(HistogramsTest, LongStringValues) {
  /*
    Ensure that HISTOGRAM_MAX_COMPARE_LENGTH is set to the value we have assumed
    throughout this test.
  */
  EXPECT_EQ(42U, HISTOGRAM_MAX_COMPARE_LENGTH);

  Value_map<String> long_strings(&my_charset_latin1, Value_map_type::STRING);

  /*
    The following three strings should be considered equal, since the 42 first
    characters are equal.
  */
  String string1("abcdefghijklmnopqrstuvwxyzabcdefghijklmnop0000",
                 &my_charset_latin1);

  String string2("abcdefghijklmnopqrstuvwxyzabcdefghijklmnop2222",
                 &my_charset_latin1);

  String string3("abcdefghijklmnopqrstuvwxyzabcdefghijklmnop1111",
                 &my_charset_latin1);

  /*
    The following three strings should be considered different, since they
    differ at the 42nd character
  */
  String string4("abcdefghijklmnopqrstuvwxyzabcdefghijklmno2222",
                 &my_charset_latin1);

  String string5("abcdefghijklmnopqrstuvwxyzabcdefghijklmno1111",
                 &my_charset_latin1);

  String string6("abcdefghijklmnopqrstuvwxyzabcdefghijklmno0000",
                 &my_charset_latin1);

  long_strings.add_values(string1, 10);
  long_strings.add_values(string2, 10);
  long_strings.add_values(string3, 10);
  long_strings.add_values(string4, 10);
  long_strings.add_values(string5, 10);
  long_strings.add_values(string6, 10);

  EXPECT_EQ(4U, long_strings.size());
}

/*
  Check that the histogram comparator only checks the 42 first bytes of long
  binary values. If the values differ at any byte after the 42nd byte, the
  binary values should be considered equal.

  This does not test any histogram per se, but the histogram comparator.
*/
TEST_F(HistogramsTest, LongBlobValues) {
  /*
    Ensure that HISTOGRAM_MAX_COMPARE_LENGTH is set to the value we have assume
    throughout this test.
  */
  EXPECT_EQ(42U, HISTOGRAM_MAX_COMPARE_LENGTH);

  Value_map<String> long_blobs(&my_charset_bin, Value_map_type::STRING);

  /*
    The following three blobs should be considered equal, since the 42 first
    bytes are equal.
  */
  const char buf1[46] = {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, 2,  2,  2,  2};

  const char buf2[46] = {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, 1,  1,  1,  1};

  const char buf3[46] = {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, 0,  0,  0,  0};

  /*
    The following three blobs should be considered different, since they differ
    at the 42nd byte
  */
  const char buf4[46] = {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, 2,  2,  2,  2,  2};

  const char buf5[46] = {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, 1,  1,  1,  1,  1};

  const char buf6[46] = {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, 0,  0,  0,  0,  0};

  long_blobs.add_values(String(buf1, 46, &my_charset_bin), 10);
  long_blobs.add_values(String(buf2, 46, &my_charset_bin), 10);
  long_blobs.add_values(String(buf3, 46, &my_charset_bin), 10);
  long_blobs.add_values(String(buf4, 46, &my_charset_bin), 10);
  long_blobs.add_values(String(buf5, 46, &my_charset_bin), 10);
  long_blobs.add_values(String(buf6, 46, &my_charset_bin), 10);

  EXPECT_EQ(4U, long_blobs.size());
}

/*
  Check that the histogram comparator only checks the 42 first characters of
  long string values, where the strings are multi-byte strings. If the strings
  differ at any character after the 42nd character, the strings should be
  considered equal.

  This does not test any histogram per se, but the histogram comparator.
*/
TEST_F(HistogramsTest, MultiByteStrings) {
  /*
    Ensure that HISTOGRAM_MAX_COMPARE_LENGTH is set to the value we have assumed
    throughout this test.
  */
  EXPECT_EQ(42U, HISTOGRAM_MAX_COMPARE_LENGTH);

  /*
    Declare the strings to have UCS2 character set, which is fixed 2 byte per
    character.
  */
  MY_CHARSET_LOADER loader;
  CHARSET_INFO *cs =
      my_collation_get_by_name(&loader, "ucs2_general_ci", MYF(0));

  Value_map<String> long_strings(cs, Value_map_type::STRING);

  String string1("", cs);
  String string2("", cs);
  String string3("", cs);
  String string4("", cs);
  String string5("", cs);
  String string6("", cs);

  /*
    The following three strings should be considered equal, since the 42 first
    characters are equal.
  */
  string1.append("abcdefghijklmnopqrstuvwxyzabcdefghijklmnop2222", 46,
                 &my_charset_latin1);
  string2.append("abcdefghijklmnopqrstuvwxyzabcdefghijklmnop1111", 46,
                 &my_charset_latin1);
  string3.append("abcdefghijklmnopqrstuvwxyzabcdefghijklmnop0000", 46,
                 &my_charset_latin1);
  /*
    The following three strings should be considered different, since they
    differ at the 42nd character
  */
  string4.append("abcdefghijklmnopqrstuvwxyzabcdefghijklmno22222", 46,
                 &my_charset_latin1);
  string5.append("abcdefghijklmnopqrstuvwxyzabcdefghijklmno11111", 46,
                 &my_charset_latin1);
  string6.append("abcdefghijklmnopqrstuvwxyzabcdefghijklmno00000", 46,
                 &my_charset_latin1);

  /*
    Since we are using UCS-2, we should have twice the amount of bytes as we
    have characters.
  */
  EXPECT_EQ(string6.numchars(), 46U);
  EXPECT_EQ(string6.length(), 92U);

  long_strings.add_values(string1, 10);
  long_strings.add_values(string2, 10);
  long_strings.add_values(string3, 10);
  long_strings.add_values(string4, 10);
  long_strings.add_values(string5, 10);
  long_strings.add_values(string6, 10);

  EXPECT_EQ(4U, long_strings.size());
}

/*
  Build an equi-height histogram with a significant amount of distinct values.
*/
TEST_F(HistogramsTest, BigEquiHeight) {
  Value_map<longlong> values(&my_charset_numeric, Value_map_type::INT);
  values.add_null_values(514);
  for (longlong i = 0; i < 100000; i++) {
    size_t frequency = static_cast<size_t>((rand() % 10000) + 1);
    values.add_values(i, frequency);
  }

  Equi_height<longlong> *histogram = Equi_height<longlong>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::INT);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_EQ(0U, histogram->get_num_buckets());
  EXPECT_EQ(0U, histogram->get_num_distinct_values());

  // Build a histogram with 200 buckets.
  size_t num_buckets = 200;
  EXPECT_FALSE(histogram->build_histogram(values, num_buckets));
  EXPECT_LE(histogram->get_num_buckets(), num_buckets);
  EXPECT_EQ(100000U, histogram->get_num_distinct_values());

  VerifyEquiHeightJSONStructure(histogram, enum_json_type::J_INT);
  VerifyEquiHeightBucketConstraintsInt(histogram);
}

/*
  Build a singleton histogram, and check if the printed time is within a few
  seconds of the current time.

  We do not add any values to the histogram, since we want it to be built as
  fast as possible.
*/
TEST_F(HistogramsTest, HistogramTimeCreated) {
  Value_map<longlong> values(&my_charset_numeric, Value_map_type::INT);

  Singleton<longlong> *histogram = Singleton<longlong>::create(
      &m_mem_root, "db1", "tbl1", "col1", Value_map_type::INT);
  ASSERT_TRUE(histogram != nullptr);

  EXPECT_EQ(0U, histogram->get_num_buckets());
  EXPECT_EQ(0U, histogram->get_num_distinct_values());

  EXPECT_FALSE(histogram->build_histogram(values, 10U));

  // Get the current time in GMT timezone.
  MYSQL_TIME current_time;
  ulonglong micro_time = my_micro_time();
  my_tz_UTC->gmt_sec_to_TIME(&current_time,
                             static_cast<my_time_t>(micro_time / 1000000));

  Json_object json_histogram;
  EXPECT_FALSE(histogram->histogram_to_json(&json_histogram));

  Json_dom *last_updated_dom = json_histogram.get("last-updated");
  Json_datetime *last_updated = down_cast<Json_datetime *>(last_updated_dom);

  longlong seconds_diff = 0;
  long microseconds_diff = 0;
  calc_time_diff(*last_updated->value(), current_time, 1, &seconds_diff,
                 &microseconds_diff);

  EXPECT_LE(seconds_diff, 2LL);
}

/*
  Check that an out-of-memory situation doesn't crash brutally, but fails
  gracefully.
*/
TEST_F(HistogramsTest, HistogramOOM) {
  Value_map<longlong> values(&my_charset_numeric, Value_map_type::INT);
  values.add_values(1, 10);
  values.add_values(2, 10);
  values.add_values(3, 10);
  values.add_values(4, 10);

  MEM_ROOT oom_mem_root(PSI_NOT_INSTRUMENTED, 32);

  /*
    Restrict the maximum capacity of the MEM_ROOT so it cannot grow anymore. But
    don't set it to 0, as this means "unlimited".
  */
  oom_mem_root.set_max_capacity(4);

  Histogram *histogram = nullptr;

  // Force an equi-height (num_buckets < num_distinct_values)
  histogram = build_histogram(&oom_mem_root, values, 1U, "db1", "tbl1", "col1");
  EXPECT_EQ(histogram, nullptr);

  // Force a singleton (num_buckets >= num_distinct_values)
  histogram =
      build_histogram(&oom_mem_root, values, 10U, "db1", "tbl1", "col1");
  EXPECT_EQ(histogram, nullptr);
}

/*
  Check that an out-of-memory situation doesn't crash brutally, but fails
  gracefully.
*/
TEST_F(HistogramsTest, EquiHeightOOM) {
  Value_map<longlong> values(&my_charset_numeric, Value_map_type::INT);
  values.add_values(1, 10);
  values.add_values(2, 10);
  values.add_values(3, 10);
  values.add_values(4, 10);

  MEM_ROOT oom_mem_root(PSI_NOT_INSTRUMENTED, 128);

  {
    /*
      Create the histogram in a new scope so that the underlying structures
      are freed before the MEM_ROOT.
    */
    Equi_height<longlong> *histogram = Equi_height<longlong>::create(
        &oom_mem_root, "db1", "tbl1", "col1", Value_map_type::INT);
    ASSERT_TRUE(histogram != nullptr);

    // Restrict the maximum capacity of the MEM_ROOT so it cannot grow anymore.
    oom_mem_root.set_max_capacity(oom_mem_root.allocated_size());
    EXPECT_TRUE(histogram->build_histogram(values, 10U));
  }
}

/*
  Check that the Equi_height factory method returns a nullptr if it runs out of
  memory during construction.
*/
TEST_F(HistogramsTest, EquiHeightCreationOOM) {
  // Successfully allocate a histogram on a MEM_ROOT.
  MEM_ROOT not_oom_mem_root(PSI_NOT_INSTRUMENTED, 128);
  Equi_height<longlong> *not_oom_histogram = Equi_height<longlong>::create(
      &not_oom_mem_root, "db1", "tbl1", "col1", Value_map_type::INT);
  EXPECT_TRUE(not_oom_histogram != nullptr);

  // Create a new MEM_ROOT and fix its capacity.
  MEM_ROOT fixed_capacity_mem_root(PSI_NOT_INSTRUMENTED, 128);
  fixed_capacity_mem_root.set_max_capacity(not_oom_mem_root.allocated_size());

  // Verify that the same allocation does not fail when we fix the capacity.
  Equi_height<longlong> *not_oom_histogram2 = Equi_height<longlong>::create(
      &fixed_capacity_mem_root, "db1", "tbl1", "col1", Value_map_type::INT);
  EXPECT_TRUE(not_oom_histogram2 != nullptr);

  // Allocate a histogram with long strings leading to an OOM error during
  // construction (not when allocating space for the histogram itself).
  MEM_ROOT fixed_capacity_mem_root2(PSI_NOT_INSTRUMENTED, 128);
  fixed_capacity_mem_root2.set_max_capacity(not_oom_mem_root.allocated_size());
  std::string long_string(1000, 'x');  // A string of length 1000.
  Equi_height<longlong> *oom_histogram = Equi_height<longlong>::create(
      &fixed_capacity_mem_root2, long_string, long_string, long_string,
      Value_map_type::INT);
  EXPECT_TRUE(oom_histogram == nullptr);
}

/*
  Check that an out-of-memory situation doesn't crash brutally, but fails
  gracefully. We need to add more than a few buckets to the default-initialized
  vector holding the buckets in order to trigger an allocation.
*/
TEST_F(HistogramsTest, SingletonOOM) {
  Value_map<longlong> values(&my_charset_numeric, Value_map_type::INT);
  size_t num_buckets = 100;
  for (longlong i = 0; i < static_cast<longlong>(num_buckets); ++i) {
    values.add_values(i, 10);
  }
  MEM_ROOT oom_mem_root(PSI_NOT_INSTRUMENTED, 128);

  {
    /*
      Create the histogram in a new scope so that the underlying structures
      are freed before the MEM_ROOT.
    */
    Singleton<longlong> *histogram = Singleton<longlong>::create(
        &oom_mem_root, "db1", "tbl1", "col1", Value_map_type::INT);
    ASSERT_TRUE(histogram != nullptr);

    // Restrict the maximum capacity of the MEM_ROOT so it cannot grow anymore.
    oom_mem_root.set_max_capacity(oom_mem_root.allocated_size());
    EXPECT_TRUE(histogram->build_histogram(values, num_buckets));
  }
}

/*
  Check that the Singleton histogram factory method returns a nullptr if it runs
  out of memory during construction.
*/
TEST_F(HistogramsTest, SingletonCreationOOM) {
  // Successfully allocate a histogram on a MEM_ROOT.
  MEM_ROOT not_oom_mem_root(PSI_NOT_INSTRUMENTED, 128);
  Singleton<longlong> *not_oom_histogram = Singleton<longlong>::create(
      &not_oom_mem_root, "db1", "tbl1", "col1", Value_map_type::INT);
  EXPECT_TRUE(not_oom_histogram != nullptr);

  // Create a new MEM_ROOT and fix its capacity.
  MEM_ROOT fixed_capacity_mem_root(PSI_NOT_INSTRUMENTED, 128);
  fixed_capacity_mem_root.set_max_capacity(not_oom_mem_root.allocated_size());

  // Verify that the same allocation does not fail when we fix the capacity.
  Singleton<longlong> *not_oom_histogram2 = Singleton<longlong>::create(
      &fixed_capacity_mem_root, "db1", "tbl1", "col1", Value_map_type::INT);
  EXPECT_TRUE(not_oom_histogram2 != nullptr);

  // Allocate a histogram with long strings leading to an OOM error during
  // construction (not when allocating space for the histogram itself).
  MEM_ROOT fixed_capacity_mem_root2(PSI_NOT_INSTRUMENTED, 128);
  fixed_capacity_mem_root2.set_max_capacity(not_oom_mem_root.allocated_size());
  std::string long_string(1000, 'x');  // A string of length 1000.
  Singleton<longlong> *oom_histogram = Singleton<longlong>::create(
      &fixed_capacity_mem_root2, long_string, long_string, long_string,
      Value_map_type::INT);
  EXPECT_TRUE(oom_histogram == nullptr);
}

}  // namespace histograms_unittest