File: item_sum.h

package info (click to toggle)
mysql-8.0 8.0.44-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,272,892 kB
  • sloc: cpp: 4,685,345; ansic: 412,712; pascal: 108,395; java: 83,641; perl: 30,221; cs: 27,067; sql: 26,594; python: 21,816; sh: 17,285; yacc: 17,169; php: 11,522; xml: 7,388; javascript: 7,083; makefile: 1,793; lex: 1,075; awk: 670; asm: 520; objc: 183; ruby: 97; lisp: 86
file content (2873 lines) | stat: -rw-r--r-- 101,342 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
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
#ifndef ITEM_SUM_INCLUDED
#define ITEM_SUM_INCLUDED

/* Copyright (c) 2000, 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 */

/* classes for sum functions */

#include <assert.h>
#include <sys/types.h>

#include <climits>
#include <cmath>
#include <cstdio>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <vector>

#include "field_types.h"  // enum_field_types
#include "m_ctype.h"
#include "m_string.h"
#include "my_alloc.h"
#include "my_compiler.h"

#include "my_inttypes.h"
#include "my_sys.h"
#include "my_table_map.h"
#include "my_time.h"
#include "my_tree.h"  // TREE
#include "mysql/udf_registration_types.h"
#include "mysql_time.h"
#include "mysqld_error.h"
#include "sql/enum_query_type.h"
#include "sql/gis/geometries_cs.h"
#include "sql/gis/wkb.h"
#include "sql/item.h"       // Item_result_field
#include "sql/item_func.h"  // Item_int_func
#include "sql/mem_root_array.h"
#include "sql/my_decimal.h"
#include "sql/parse_location.h"     // POS
#include "sql/parse_tree_window.h"  // PT_window
#include "sql/sql_base.h"
#include "sql/sql_const.h"
#include "sql/sql_list.h"
#include "sql/sql_udf.h"     // udf_handler
#include "sql/thr_malloc.h"  // THR_MALLOC
#include "sql/window_lex.h"
#include "sql_string.h"
#include "template_utils.h"

class Field;
class Item_sum;
class Json_array;
class Json_object;
class Json_wrapper;
class PT_item_list;
class PT_order_list;
class Query_block;
class THD;
class Temp_table_param;
class Window;
struct ORDER;
struct Parse_context;
struct TABLE;
struct Window_evaluation_requirements;

/**
  The abstract base class for the Aggregator_* classes.
  It implements the data collection functions (setup/add/clear)
  as either pass-through to the real functionality or
  as collectors into an Unique (for distinct) structure.

  Note that update_field/reset_field are not in that
  class, because they're simply not called when
  GROUP BY/DISTINCT can be handled with help of index on grouped
  fields (allow_group_via_temp_table is false);
*/

class Aggregator {
  friend class Item_sum;
  friend class Item_sum_sum;
  friend class Item_sum_count;
  friend class Item_sum_avg;

  /*
    All members are protected as this class is not usable outside of an
    Item_sum descendant.
  */
 protected:
  /* the aggregate function class to act on */
  Item_sum *item_sum;

 public:
  Aggregator(Item_sum *arg) : item_sum(arg) {}
  virtual ~Aggregator() = default;

  enum Aggregator_type { SIMPLE_AGGREGATOR, DISTINCT_AGGREGATOR };
  virtual Aggregator_type Aggrtype() = 0;

  /**
    Called before adding the first row.
    Allocates and sets up the internal aggregation structures used,
    e.g. the Unique instance used to calculate distinct.
  */
  virtual bool setup(THD *) = 0;

  /**
    Called when we need to wipe out all the data from the aggregator:
    all the values accumulated and all the state.
    Cleans up the internal structures and resets them to their initial state.
  */
  virtual void clear() = 0;

  /**
    Called when there's a new value to be aggregated.
    Updates the internal state of the aggregator to reflect the new value.
  */
  virtual bool add() = 0;

  /**
    Called when there are no more data and the final value is to be retrieved.
    Finalises the state of the aggregator, so the final result can be retrieved.
  */
  virtual void endup() = 0;

  /** Decimal value of being-aggregated argument */
  virtual my_decimal *arg_val_decimal(my_decimal *value) = 0;
  /** Floating point value of being-aggregated argument */
  virtual double arg_val_real() = 0;
  /**
    NULLness of being-aggregated argument.

    @param use_null_value Optimization: to determine if the argument is NULL
    we must, in the general case, call is_null() on it, which itself might
    call val_*() on it, which might be costly. If you just have called
    arg_val*(), you can pass use_null_value=true; this way, arg_is_null()
    might avoid is_null() and instead do a cheap read of the Item's null_value
    (updated by arg_val*()).
  */
  virtual bool arg_is_null(bool use_null_value) = 0;
};

/**
  Class Item_sum is the base class used for special expressions that SQL calls
  'set functions'. These expressions are formed with the help of aggregate
  functions such as SUM, MAX, GROUP_CONCAT etc.
  Class Item_sum is also the base class for Window functions; the text below
  first documents set functions, then window functions.

 GENERAL NOTES

  A set function cannot be used in all positions where expressions are accepted.
  There are some quite explicable restrictions for the use of set functions.

  In the query:

    SELECT AVG(b) FROM t1 WHERE SUM(b) > 20 GROUP by a

  the set function AVG(b) is valid, while the usage of SUM(b) is invalid.
  A WHERE condition must contain expressions that can be evaluated for each row
  of the table. Yet the expression SUM(b) can be evaluated only for each group
  of rows with the same value of column a.
  In the query:

    SELECT AVG(b) FROM t1 WHERE c > 30 GROUP BY a HAVING SUM(b) > 20

  both set function expressions AVG(b) and SUM(b) are valid.

  We can say that in a query without nested selects an occurrence of a
  set function in an expression of the SELECT list or/and in the HAVING
  clause is valid, while in the WHERE clause, FROM clause or GROUP BY clause
  it is invalid.

  The general rule to detect whether a set function is valid in a query with
  nested subqueries is much more complicated.

  Consider the following query:

    SELECT t1.a FROM t1 GROUP BY t1.a
      HAVING t1.a > ALL (SELECT t2.c FROM t2 WHERE SUM(t1.b) < t2.c).

  The set function SUM(b) is used here in the WHERE clause of the subquery.
  Nevertheless it is valid since it is contained in the HAVING clause of the
  outer query. The expression SUM(t1.b) is evaluated for each group defined
 in the main query, not for groups of the subquery.

  The problem of finding the query where to aggregate a particular
  set function is not so simple as it seems to be.

  In the query:
    SELECT t1.a FROM t1 GROUP BY t1.a
     HAVING t1.a > ALL(SELECT t2.c FROM t2 GROUP BY t2.c
                         HAVING SUM(t1.a) < t2.c)

  the set function can be evaluated in both the outer and the inner query block.
  If we evaluate SUM(t1.a) for the outer query then we get the value of t1.a
  multiplied by the cardinality of a group in table t1. In this case,
  SUM(t1.a) is used as a constant value in each correlated subquery.
  But SUM(t1.a) can also be evaluated for the inner query.
  In this case t1.a will be a constant value for each correlated subquery and
  summation is performed for each group of table t2.
  (Here it makes sense to remind that the query

    SELECT c FROM t GROUP BY a HAVING SUM(1) < a

  is quite valid in our SQL).

  So depending on what query block we assign the set function to we
  can get different results.

  The general rule to detect the query block Q where a set function will be
  aggregated (evaluated) can be formulated as follows.

  Reference: SQL2011 @<set function specification@> syntax rules 6 and 7.

  Consider a set function S(E) where E is an expression which contains
  column references C1, ..., Cn. Resolve all column references Ci against
  the query block Qi containing the set function S(E). Let Q be the innermost
  query block of all query blocks Qi. (It should be noted here that S(E)
  in no way can be aggregated in the query block containing the subquery Q,
  otherwise S(E) would refer to at least one unbound column reference).
  If S(E) is used in a construct of Q where set functions are allowed then
  we aggregate S(E) in Q.
  Otherwise:
  - if ANSI SQL mode is enabled (MODE_ANSI), then report an error.
  - otherwise, look for the innermost query block containing S(E) of those
    where usage of S(E) is allowed. The place of aggregation depends on which
    clause the subquery is contained within; It will be different when
    contained in a WHERE clause versus in the select list or in HAVING clause.

  Let's demonstrate how this rule is applied to the following queries.

  1. SELECT t1.a FROM t1 GROUP BY t1.a
       HAVING t1.a > ALL(SELECT t2.b FROM t2 GROUP BY t2.b
                           HAVING t2.b > ALL(SELECT t3.c FROM t3 GROUP BY t3.c
                                                HAVING SUM(t1.a+t2.b) < t3.c))
  For this query the set function SUM(t1.a+t2.b) contains t1.a and t2.b
  with t1.a defined in the outermost query, and t2.b defined for its
  subquery. The set function is contained in the HAVING clause of the subquery
  and can be evaluated in this subquery.

  2. SELECT t1.a FROM t1 GROUP BY t1.a
       HAVING t1.a > ALL(SELECT t2.b FROM t2
                           WHERE t2.b > ALL (SELECT t3.c FROM t3 GROUP BY t3.c
                                               HAVING SUM(t1.a+t2.b) < t3.c))
  The set function SUM(t1.a+t2.b) is contained in the WHERE clause of the second
  query block - the outermost query block where t1.a and t2.b are defined.
  If we evaluate the function in this subquery we violate the context rules.
  So we evaluate the function in the third query block (over table t3) where it
  is used under the HAVING clause; if in ANSI SQL mode, an error is thrown.

  3. SELECT t1.a FROM t1 GROUP BY t1.a
       HAVING t1.a > ALL(SELECT t2.b FROM t2
                           WHERE t2.b > ALL (SELECT t3.c FROM t3
                                               WHERE SUM(t1.a+t2.b) < t3.c))
  In this query, evaluation of SUM(t1.a+t2.b) is not valid neither in the second
  nor in the third query block.

  Set functions can generally not be nested. In the query

    SELECT t1.a from t1 GROUP BY t1.a HAVING AVG(SUM(t1.b)) > 20

  the expression SUM(b) is not valid, even though it is contained inside
  a HAVING clause.
  However, it is acceptable in the query:

    SELECT t.1 FROM t1 GROUP BY t1.a HAVING SUM(t1.b) > 20.

  An argument of a set function does not have to be a simple column reference
  as seen in examples above. This can be a more complex expression

    SELECT t1.a FROM t1 GROUP BY t1.a HAVING SUM(t1.b+1) > 20.

  The expression SUM(t1.b+1) has clear semantics in this context:
  we sum up the values of t1.b+1 where t1.b varies for all values within a
  group of rows that contain the same t1.a value.

  A set function for an outer query yields a constant value within a subquery.
  So the semantics of the query

    SELECT t1.a FROM t1 GROUP BY t1.a
      HAVING t1.a IN (SELECT t2.c FROM t2 GROUP BY t2.c
                        HAVING AVG(t2.c+SUM(t1.b)) > 20)

  is still clear. For a group of rows with the same value for t1.a, calculate
  the value of SUM(t1.b) as 's'. This value is substituted in the subquery:

    SELECT t2.c FROM t2 GROUP BY t2.c HAVING AVG(t2.c+s)

  By the same reason the following query with a subquery

    SELECT t1.a FROM t1 GROUP BY t1.a
      HAVING t1.a IN (SELECT t2.c FROM t2 GROUP BY t2.c
                        HAVING AVG(SUM(t1.b)) > 20)
  is also valid.

 IMPLEMENTATION NOTES

  The member base_query_block contains a reference to the query block that the
  set function is contained within.

  The member aggr_query_block contains a reference to the query block where the
  set function is aggregated.

  The field max_aggr_level holds the maximum of the nest levels of the
  unbound column references contained in the set function. A column reference
  is unbound within a set function if it is not bound by any subquery
  used as a subexpression in this function. A column reference is bound by
  a subquery if it is a reference to the column by which the aggregation
  of some set function that is used in the subquery is calculated.
  For the set function used in the query

    SELECT t1.a FROM t1 GROUP BY t1.a
      HAVING t1.a > ALL(SELECT t2.b FROM t2 GROUP BY t2.b
                          HAVING t2.b > ALL(SELECT t3.c FROM t3 GROUP BY t3.c
                                              HAVING SUM(t1.a+t2.b) < t3.c))

  the value of max_aggr_level is equal to 1 since t1.a is bound in the main
  query, and t2.b is bound by the first subquery whose nest level is 1.
  Obviously a set function cannot be aggregated in a subquery whose
  nest level is less than max_aggr_level. (Yet it can be aggregated in the
  subqueries whose nest level is greater than max_aggr_level.)
  In the query
    SELECT t1.a FROM t1 HAVING AVG(t1.a+(SELECT MIN(t2.c) FROM t2))

  the value of the max_aggr_level for the AVG set function is 0 since
  the reference t2.c is bound in the subquery.

  If a set function contains no column references (like COUNT(*)),
  max_aggr_level is -1.

  The field 'max_sum_func_level' is to contain the maximum of the
  nest levels of the set functions that are used as subexpressions of
  the arguments of the given set function, but not aggregated in any
  subquery within this set function. A nested set function s1 can be
  used within set function s0 only if s1.max_sum_func_level <
  s0.max_sum_func_level. Set function s1 is considered as nested
  for set function s0 if s1 is not calculated in any subquery
  within s0.

  A set function that is used as a subexpression in an argument of another
  set function refers to the latter via the field 'in_sum_func'.

  The condition imposed on the usage of set functions are checked when
  we traverse query subexpressions with the help of the recursive method
  fix_fields. When we apply this method to an object of the class
  Item_sum, first, on the descent, we call the method init_sum_func_check
  that initialize members used at checking. Then, on the ascent, we
  call the method check_sum_func that validates the set function usage
  and reports an error if it is invalid.
  The method check_sum_func serves to link the items for the set functions
  that are aggregated in the containing query blocks. Circular chains of such
  functions are attached to the corresponding Query_block structures
  through the field inner_sum_func_list.

  Exploiting the fact that the members mentioned above are used in one
  recursive function we could have allocated them on the thread stack.
  Yet we don't do it now.

  It is assumed that the nesting level of subqueries does not exceed 63
  (valid nesting levels are stored in a 64-bit bitmap called nesting_map).
  The assumption is enforced in LEX::new_query().

  WINDOW FUNCTIONS

  Most set functions (e.g. SUM, COUNT, AVG) can also be used as window
  functions. In that case, notable differences compared to set functions are:
  - not using any Aggregator
  - not supporting DISTINCT
  - val_*() does more than returning the function's current value: it
  first accumulates the function's argument into the function's
  state. Execution (e.g. end_write_wf()) manipulates temporary tables which
  contain input for WFs; each input row is passed to copy_funcs() which calls
  the WF's val_*() to accumulate it.
*/

class Item_sum : public Item_func {
  friend class Aggregator_distinct;
  friend class Aggregator_simple;

 protected:
  /**
    Aggregator class instance. Not set initially. Allocated only after
    it is determined if the incoming data are already distinct.
  */
  Aggregator *aggr{nullptr};

  /**
    If sum is a window function, this field contains the window.
  */
  PT_window *m_window{nullptr};
  /**
    True if we have already resolved this window functions window reference.
    Used in execution of prepared statement to avoid re-resolve.
  */
  bool m_window_resolved{false};

 private:
  /**
    Used in making ROLLUP. Set for the ROLLUP copies of the original
    Item_sum and passed to create_tmp_field() to cause it to work
    over the temp table buffer that is referenced by
    Item_result_field::result_field.
  */
  bool force_copy_fields{false};

  /**
    Indicates how the aggregate function was specified by the parser :
     true if it was written as AGGREGATE(DISTINCT),
     false if it was AGGREGATE()
  */
  bool with_distinct{false};

 public:
  bool has_force_copy_fields() const { return force_copy_fields; }
  bool has_with_distinct() const { return with_distinct; }

  enum Sumfunctype {
    COUNT_FUNC,           // COUNT
    COUNT_DISTINCT_FUNC,  // COUNT (DISTINCT)
    SUM_FUNC,             // SUM
    SUM_DISTINCT_FUNC,    // SUM (DISTINCT)
    AVG_FUNC,             // AVG
    AVG_DISTINCT_FUNC,    // AVG (DISTINCT)
    MIN_FUNC,             // MIN
    MAX_FUNC,             // MAX
    STD_FUNC,             // STD/STDDEV/STDDEV_POP
    VARIANCE_FUNC,        // VARIANCE/VAR_POP and VAR_SAMP
    SUM_BIT_FUNC,         // BIT_AND, BIT_OR and BIT_XOR
    UDF_SUM_FUNC,         // user defined functions
    GROUP_CONCAT_FUNC,    // GROUP_CONCAT
    JSON_AGG_FUNC,        // JSON_ARRAYAGG and JSON_OBJECTAGG
    ROW_NUMBER_FUNC,      // Window functions
    RANK_FUNC,
    DENSE_RANK_FUNC,
    CUME_DIST_FUNC,
    PERCENT_RANK_FUNC,
    NTILE_FUNC,
    LEAD_LAG_FUNC,
    FIRST_LAST_VALUE_FUNC,
    NTH_VALUE_FUNC,
    ROLLUP_SUM_SWITCHER_FUNC,
    GEOMETRY_AGGREGATE_FUNC
  };

  /**
    @note most member variables below serve only for grouped aggregate
    functions.
  */

  /**
    For a group aggregate which is aggregated into an outer query
    block; none, or just the first or both cells may be non-zero. They are
    filled with references to the group aggregate (for example if it is the
    argument of a function; it is then a pointer to that function's args[i]
    pointer).
  */
  Item **referenced_by[2];
  /// next in the circular chain of registered objects
  Item_sum *next_sum{nullptr};
  Item_sum *in_sum_func;          ///< the containing set function if any
  Query_block *base_query_block;  ///< query block where function is placed
  /**
    For a group aggregate, query block where function is aggregated. For a
    window function, nullptr, as such function is always aggregated in
    base_query_block, as it mustn't contain any outer reference.
  */
  Query_block *aggr_query_block;
  int8 max_aggr_level;  ///< max level of unbound column references
  int8
      max_sum_func_level;  ///< max level of aggregation for contained functions
  bool allow_group_via_temp_table;  ///< If incremental update of fields is
                                    ///< supported.
  /**
    WFs are forbidden when resolving Item_sum; this member is used to restore
    WF allowance status afterwards.
  */
  nesting_map save_deny_window_func;

 protected:
  /**
    True means that this field has been evaluated during optimization.
    When set, used_tables() returns zero and const_item() returns true.
    The value must be reset to false after execution.
  */
  bool forced_const{false};

  /// true if the function is resolved to be always NULL
  bool m_null_resolved{false};
  /// true if the function is determined to be NULL at start of execution
  bool m_null_executed{false};

  static ulonglong ram_limitation(THD *thd);

 public:
  void mark_as_sum_func();
  void mark_as_sum_func(Query_block *);

  Item_sum(const POS &pos, PT_window *w)
      : Item_func(pos), m_window(w), allow_group_via_temp_table(true) {}

  Item_sum(Item *a)
      : Item_func(a), m_window(nullptr), allow_group_via_temp_table(true) {
    mark_as_sum_func();
  }

  Item_sum(const POS &pos, Item *a, PT_window *w)
      : Item_func(pos, a), m_window(w), allow_group_via_temp_table(true) {}

  Item_sum(const POS &pos, Item *a, Item *b, PT_window *w)
      : Item_func(pos, a, b), m_window(w), allow_group_via_temp_table(true) {}

  Item_sum(const POS &pos, PT_item_list *opt_list, PT_window *w);

  /// Copy constructor, need to perform subqueries with temporary tables
  Item_sum(THD *thd, const Item_sum *item);

  bool itemize(Parse_context *pc, Item **res) override;
  Type type() const override { return SUM_FUNC_ITEM; }
  virtual enum Sumfunctype sum_func() const = 0;

  // Differs only for Item_rollup_sum_switcher.
  virtual enum Sumfunctype real_sum_func() const { return sum_func(); }

  /**
    Resets the aggregate value to its default and aggregates the current
    value of its attribute(s).
  */
  inline bool reset_and_add() {
    aggregator_clear();
    return aggregator_add();
  }

  /*
    Called when new group is started and results are being saved in
    a temporary table. Similarly to reset_and_add() it resets the
    value to its default and aggregates the value of its
    attribute(s), but must also store it in result_field.
    This set of methods (result_item(), reset_field, update_field()) of
    Item_sum is used only if allow_group_via_temp_table is true. Otherwise
    copy_or_same() is used to obtain a copy of this item.
  */
  virtual void reset_field() = 0;
  /*
    Called for each new value in the group, when temporary table is in use.
    Similar to add(), but uses temporary table field to obtain current value,
    Updated value is then saved in the field.
  */
  virtual void update_field() = 0;
  virtual bool keep_field_type() const { return false; }
  bool resolve_type(THD *) override;
  virtual Item *result_item(Field *field) {
    Item_field *item = new Item_field(field);
    if (item == nullptr) return nullptr;
    // Aggregated fields have no reference to an underlying table
    assert(item->original_db_name() == nullptr &&
           item->original_table_name() == nullptr);
    // Break the connection to the original field since this is an aggregation
    item->set_original_field_name(nullptr);
    return item;
  }
  table_map used_tables() const override {
    return forced_const ? 0 : used_tables_cache;
  }
  table_map not_null_tables() const override { return used_tables(); }
  void update_used_tables() override;
  void fix_after_pullout(Query_block *parent_query_block,
                         Query_block *removed_query_block) override;
  void add_used_tables_for_aggr_func();
  bool is_null() override { return null_value; }

  void make_const() {
    // "forced_const" will make used_tables() return zero for this object
    forced_const = true;
  }
  void print(const THD *thd, String *str,
             enum_query_type query_type) const override;
  bool eq(const Item *item, bool binary_cmp) const override;
  /**
    Mark an aggregate as having no rows.

    This function is called by the execution engine to assign 'NO ROWS
    FOUND' value to an aggregate item, when the underlying result set
    has no rows. Such value, in a general case, may be different from
    the default value of the item after 'clear()': e.g. a numeric item
    may be initialized to 0 by clear() and to NULL by
    no_rows_in_result().
  */
  void no_rows_in_result() override {
    set_aggregator(with_distinct ? Aggregator::DISTINCT_AGGREGATOR
                                 : Aggregator::SIMPLE_AGGREGATOR);
    aggregator_clear();
  }
  virtual void make_unique() { force_copy_fields = true; }
  virtual Field *create_tmp_field(bool group, TABLE *table);

  /// argument used by walk method collect_grouped_aggregates ("cga")
  struct Collect_grouped_aggregate_info {
    /// accumulated all aggregates found
    std::vector<Item_sum *> list;
    std::set<Item_sum *> aggregates_that_were_hidden;
    /**
      The query block we walk from. All found aggregates must aggregate in
      this; if some aggregate in outer query blocks, break off transformation.
    */
    Query_block *m_query_block{nullptr};
    /// true: break off transformation
    bool m_break_off{false};
    /// true: an aggregate aggregates outside m_query_block
    bool m_outside{false};
    Collect_grouped_aggregate_info(Query_block *select)
        : m_query_block(select) {}
  };

  bool collect_grouped_aggregates(uchar *) override;
  Item *replace_aggregate(uchar *) override;
  bool collect_scalar_subqueries(uchar *) override;
  bool collect_item_field_or_view_ref_processor(uchar *) override;

  bool clean_up_after_removal(uchar *arg) override;
  bool aggregate_check_group(uchar *arg) override;
  bool aggregate_check_distinct(uchar *arg) override;
  bool has_aggregate_ref_in_group_by(uchar *arg) override;
  bool init_sum_func_check(THD *thd);
  bool check_sum_func(THD *thd, Item **ref);

  Item *set_arg(THD *thd, uint i, Item *new_val) override;
  /// @todo delete this when we no longer support temporary transformations
  Item **get_arg_ptr(uint i) { return &args[i]; }

  bool fix_fields(THD *thd, Item **ref) override;

  /**
    Signal to the function that its arguments may have changed,
    and that any internal caches etc. based on those arguments
    must be updated accordingly.

    This is used by the hypergraph optimizer when it rewrites
    arguments to window functions to take into account that they
    have been materialized into temporary tables, or that they
    should read their values from the framebuffer.
  */
  virtual void update_after_wf_arguments_changed(THD *) {}

  /**
    Called to initialize the aggregator.
  */

  virtual bool aggregator_setup(THD *thd) { return aggr->setup(thd); }

  /**
    Called to cleanup the aggregator.
  */

  inline void aggregator_clear() { aggr->clear(); }

  /**
    Called to add value to the aggregator.
  */

  inline bool aggregator_add() { return aggr->add(); }

  /* stores the declared DISTINCT flag (from the parser) */
  void set_distinct(bool distinct) {
    with_distinct = distinct;
    allow_group_via_temp_table = !with_distinct;
  }

  /*
    Set the type of aggregation : DISTINCT or not.

    May be called multiple times.
  */

  virtual int set_aggregator(Aggregator::Aggregator_type aggregator);

  virtual void clear() = 0;
  virtual bool add() = 0;
  virtual bool setup(THD *) { return false; }

  /**
    Only relevant for aggregates qua window functions. Checks semantics after
    windows have been set up and checked. Window functions have specific
    requirements on the window specifications. Used at resolution time.

    @param thd                    Current thread
    @param select                 The current select
    @param [out] reqs             Holds collected requirements from this wf

    @returns true if error
   */
  virtual bool check_wf_semantics1(THD *thd, Query_block *select,
                                   Window_evaluation_requirements *reqs);

  /**
    Like check_wf_semantics1.
    For checks which cannot be done in resolution phase (mostly those for
    input parameters which can be '?' and must be >=0: value isn't known
    before execution phase).
  */
  virtual bool check_wf_semantics2(Window_evaluation_requirements *reqs
                                   [[maybe_unused]]) {
    return false;
  }

  void split_sum_func(THD *thd, Ref_item_array ref_item_array,
                      mem_root_deque<Item *> *fields) override;

  void cleanup() override;

  Window *window() { return m_window; }
  const Window *window() const { return m_window; }
  bool reset_wf_state(uchar *arg) override;

  /**
    All aggregates are framing, i.e. they work on the window's frame. If none
    is defined, the frame is by default the entire partition, unless ORDER BY
    is defined, in which case it is the set of rows from the start of the
    partition to and including the peer set of the current row.

    Some window functions are not framing, i.e. they always work on the entire
    partition. For such window functions, the method is overridden to
    return false.
  */
  virtual bool framing() const { return true; }

  /**
    Only for framing window functions. True if this function only needs to
    read one row per frame.
  */
  virtual bool uses_only_one_row() const { return false; }

  /**
    Return true if we need to make two passes over the rows in the partition -
    either because we need the cardinality of it (and we need to read all
    rows to detect the next partition), or we need to have all partition rows
    available to evaluate the window function for some other reason, e.g.
    we may need the last row in the partition in the frame buffer to be able
    to evaluate LEAD.
  */
  virtual bool needs_partition_cardinality() const { return false; }

  /**
    Common initial actions for window functions. For non-buffered processing
    ("on-the-fly"), check partition change and possible reset partition
    state. In this case return false.
    For buffered processing, if windowing state m_do_copy_null is true, set
    null_value to is_nullable() and return true.

    @return true if case two above holds, else false
  */
  bool wf_common_init();

  /// Overridden by Item_rollup_sum_switcher.
  virtual bool is_rollup_sum_wrapper() const { return false; }
  /**
   * In case we are an Item_rollup_sum_switcher,
   * return the underlying Item_sum, otherwise, return this.
   * Overridden by Item_rollup_sum_switcher.
   */
  virtual const Item_sum *unwrap_sum() const { return this; }
  /// Non-const version
  virtual Item_sum *unwrap_sum() { return this; }

 protected:
  /*
    Raise an error (ER_NOT_SUPPORTED_YET) with the detail that this
    function is not yet supported as a window function.
  */
  void unsupported_as_wf() {
    char buff[STRING_BUFFER_USUAL_SIZE];
    snprintf(buff, sizeof(buff), "%s as window function", func_name());
    my_error(ER_NOT_SUPPORTED_YET, MYF(0), buff);
  }
};

class Unique;

/**
 The distinct aggregator.
 Implements AGGFN (DISTINCT ..)
 Collects all the data into an Unique (similarly to what Item_sum_distinct
 does currently) and then (if applicable) iterates over the list of
 unique values and pumps them back into its object
*/

class Aggregator_distinct : public Aggregator {
  friend class Item_sum_sum;

  /*
    flag to prevent consecutive runs of endup(). Normally in endup there are
    expensive calculations (like walking the distinct tree for example)
    which we must do only once if there are no data changes.
    We can re-use the data for the second and subsequent val_xxx() calls.
    endup_done set to true also means that the calculated values for
    the aggregate functions are correct and don't need recalculation.
  */
  bool endup_done;

  /*
    Used depending on the type of the aggregate function and the presence of
    blob columns in it:
    - For COUNT(DISTINCT) and no blob fields this points to a real temporary
      table. It's used as a hash table.
    - For AVG/SUM(DISTINCT) or COUNT(DISTINCT) with blob fields only the
      in-memory data structure of a temporary table is constructed.
      It's used by the Field classes to transform data into row format.
  */
  TABLE *table;

  /*
    An array of field lengths on row allocated and used only for
    COUNT(DISTINCT) with multiple columns and no blobs. Used in
    Aggregator_distinct::composite_key_cmp (called from Unique to compare
    nodes
  */
  uint32 *field_lengths;

  /*
    Used in conjunction with 'table' to support the access to Field classes
    for COUNT(DISTINCT). Needed by copy_fields()/copy_funcs().
  */
  Temp_table_param *tmp_table_param;

  /*
    If there are no blobs in the COUNT(DISTINCT) arguments, we can use a tree,
    which is faster than heap table. In that case, we still use the table
    to help get things set up, but we insert nothing in it.
    For AVG/SUM(DISTINCT) we always use this tree (as it takes a single
    argument) to get the distinct rows.
  */
  Unique *tree;

  /*
    The length of the temp table row. Must be a member of the class as it
    gets passed down to simple_raw_key_cmp () as a compare function argument
    to Unique. simple_raw_key_cmp () is used as a fast comparison function
    when the entire row can be binary compared.
  */
  uint tree_key_length;

  enum Const_distinct {
    NOT_CONST = 0,
    /**
      Set to true if the result is known to be always NULL.
      If set deactivates creation and usage of the temporary table (in the
      'table' member) and the Unique instance (in the 'tree' member) as well as
      the calculation of the final value on the first call to
      @c Item_sum::val_xxx(),
      @c Item_avg::val_xxx(),
      @c Item_count::val_xxx().
     */
    CONST_NULL,
    /**
      Set to true if count distinct is on only const items. Distinct on a const
      value will always be the constant itself. And count distinct of the same
      would always be 1. Similar to CONST_NULL, it avoids creation of temporary
      table and the Unique instance.
     */
    CONST_NOT_NULL
  } const_distinct;

  /**
    When feeding back the data in endup() from Unique/temp table back to
    Item_sum::add() methods we must read the data from Unique (and not
    recalculate the functions that are given as arguments to the aggregate
    function.
    This flag is to tell the arg_*() methods to take the data from the Unique
    instead of calling the relevant val_..() method.
  */
  bool use_distinct_values;

 public:
  Aggregator_distinct(Item_sum *sum)
      : Aggregator(sum),
        table(nullptr),
        tmp_table_param(nullptr),
        tree(nullptr),
        const_distinct(NOT_CONST),
        use_distinct_values(false) {}
  ~Aggregator_distinct() override;
  Aggregator_type Aggrtype() override { return DISTINCT_AGGREGATOR; }

  bool setup(THD *) override;
  void clear() override;
  bool add() override;
  void endup() override;
  my_decimal *arg_val_decimal(my_decimal *value) override;
  double arg_val_real() override;
  bool arg_is_null(bool use_null_value) override;

  bool unique_walk_function(void *element);
  static int composite_key_cmp(const void *arg, const void *a, const void *b);
};

/**
  The pass-through aggregator.
  Implements AGGFN (DISTINCT ..) by knowing it gets distinct data on input.
  So it just pumps them back to the Item_sum descendant class.
*/
class Aggregator_simple : public Aggregator {
 public:
  Aggregator_simple(Item_sum *sum) : Aggregator(sum) {}
  Aggregator_type Aggrtype() override { return Aggregator::SIMPLE_AGGREGATOR; }

  bool setup(THD *thd) override { return item_sum->setup(thd); }
  void clear() override { item_sum->clear(); }
  bool add() override { return item_sum->add(); }
  void endup() override {}
  my_decimal *arg_val_decimal(my_decimal *value) override;
  double arg_val_real() override;
  bool arg_is_null(bool use_null_value) override;
};

class Item_sum_num : public Item_sum {
  typedef Item_sum super;

 protected:
  /*
   val_xxx() functions may be called several times during the execution of a
   query. Derived classes that require extensive calculation in val_xxx()
   maintain cache of aggregate value. This variable governs the validity of
   that cache.
  */
  bool is_evaluated;

 public:
  Item_sum_num(const POS &pos, Item *item_par, PT_window *window)
      : Item_sum(pos, item_par, window), is_evaluated(false) {}

  Item_sum_num(const POS &pos, PT_item_list *list, PT_window *w)
      : Item_sum(pos, list, w), is_evaluated(false) {}

  Item_sum_num(THD *thd, Item_sum_num *item)
      : Item_sum(thd, item), is_evaluated(item->is_evaluated) {}
  enum_field_types default_data_type() const override {
    return MYSQL_TYPE_DOUBLE;
  }

  Item_sum_num(Item *item_par) : Item_sum(item_par), is_evaluated(false) {}

  bool fix_fields(THD *, Item **) override;
  longlong val_int() override {
    assert(fixed == 1);
    return llrint_with_overflow_check(val_real()); /* Real as default */
  }
  String *val_str(String *str) override;
  my_decimal *val_decimal(my_decimal *) override;
  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
    return get_date_from_numeric(ltime, fuzzydate); /* Decimal or real */
  }
  bool get_time(MYSQL_TIME *ltime) override {
    return get_time_from_numeric(ltime); /* Decimal or real */
  }
  void reset_field() override;
};

class Item_sum_int : public Item_sum_num {
 public:
  Item_sum_int(const POS &pos, Item *item_par, PT_window *w)
      : Item_sum_num(pos, item_par, w) {
    set_data_type_longlong();
  }

  Item_sum_int(const POS &pos, PT_item_list *list, PT_window *w)
      : Item_sum_num(pos, list, w) {
    set_data_type_longlong();
  }

  Item_sum_int(THD *thd, Item_sum_int *item) : Item_sum_num(thd, item) {
    set_data_type_longlong();
  }

  Item_sum_int(Item *item_par) : Item_sum_num(item_par) {
    set_data_type_longlong();
  }

  double val_real() override {
    assert(fixed);
    return static_cast<double>(val_int());
  }
  String *val_str(String *str) override;
  my_decimal *val_decimal(my_decimal *) override;
  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
    return get_date_from_int(ltime, fuzzydate);
  }
  bool get_time(MYSQL_TIME *ltime) override { return get_time_from_int(ltime); }
  enum Item_result result_type() const override { return INT_RESULT; }
};

class Item_sum_sum : public Item_sum_num {
 protected:
  Item_result hybrid_type;
  double sum;
  my_decimal dec_buffs[2];
  uint curr_dec_buff;
  bool resolve_type(THD *thd) override;
  /**
    Execution state: this is for counting rows entering and leaving the window
    frame, see #m_frame_null_count.
  */
  ulonglong m_count;

  /**
    Execution state: this is for counting NULLs of rows entering and leaving
    the window frame, when we use optimized inverse-based computations. By
    comparison with m_count we can know how many non-NULLs are in the frame.
  */
  ulonglong m_frame_null_count;

 public:
  Item_sum_sum(const POS &pos, Item *item_par, bool distinct, PT_window *window)
      : Item_sum_num(pos, item_par, window),
        hybrid_type(INVALID_RESULT),
        m_count(0),
        m_frame_null_count(0) {
    set_distinct(distinct);
  }

  Item_sum_sum(THD *thd, Item_sum_sum *item);
  enum Sumfunctype sum_func() const override {
    return has_with_distinct() ? SUM_DISTINCT_FUNC : SUM_FUNC;
  }
  void clear() override;
  bool add() override;
  double val_real() override;
  longlong val_int() override;
  String *val_str(String *str) override;
  my_decimal *val_decimal(my_decimal *) override;
  enum Item_result result_type() const override { return hybrid_type; }
  bool check_wf_semantics1(THD *thd, Query_block *select,
                           Window_evaluation_requirements *reqs) override;
  void no_rows_in_result() override;
  void reset_field() override;
  void update_field() override;
  const char *func_name() const override { return "sum"; }
  Item *copy_or_same(THD *thd) override;
};

class Item_sum_count : public Item_sum_int {
  longlong count;

  friend class Aggregator_distinct;

  void clear() override;
  bool add() override;
  void cleanup() override;

 public:
  Item_sum_count(const POS &pos, Item *item_par, PT_window *w)
      : Item_sum_int(pos, item_par, w), count(0) {}
  Item_sum_count(Item_int *number) : Item_sum_int(number), count(0) {}
  /**
    Constructs an instance for COUNT(DISTINCT)

    @param pos  Position of token in the parser.
    @param list A list of the arguments to the aggregate function
    @param w    A window, if COUNT is used as a windowing function

    This constructor is called by the parser only for COUNT (DISTINCT).
  */

  Item_sum_count(const POS &pos, PT_item_list *list, PT_window *w)
      : Item_sum_int(pos, list, w), count(0) {
    set_distinct(true);
  }
  Item_sum_count(THD *thd, Item_sum_count *item)
      : Item_sum_int(thd, item), count(item->count) {}
  enum Sumfunctype sum_func() const override {
    return has_with_distinct() ? COUNT_DISTINCT_FUNC : COUNT_FUNC;
  }
  bool resolve_type(THD *thd) override {
    if (param_type_is_default(thd, 0, -1)) return true;
    set_nullable(false);
    null_value = false;
    return false;
  }
  void no_rows_in_result() override { count = 0; }
  void make_const(longlong count_arg) {
    count = count_arg;
    Item_sum::make_const();
  }
  longlong val_int() override;
  void reset_field() override;
  void update_field() override;
  const char *func_name() const override { return "count"; }
  Item *copy_or_same(THD *thd) override;
};

/* Item to get the value of a stored sum function */

class Item_sum_avg;
class Item_sum_bit;

/**
  This is used in connection which a parent Item_sum:
  - which can produce different result types (is "hybrid")
  - which stores function's value into a temporary table's column (one
  row per group).
  - which stores in the column some internal piece of information which should
  not be returned to the user, so special implementations are needed.
*/
class Item_sum_hybrid_field : public Item_result_field {
 protected:
  /// The tmp table's column containing the value of the set function.
  Field *field;
  /// Stores the Item's result type.
  Item_result hybrid_type;

 public:
  enum Item_result result_type() const override { return hybrid_type; }
  bool mark_field_in_map(uchar *arg) override {
    /*
      Filesort (find_all_keys) over a temporary table collects the columns it
      needs.
    */
    return Item::mark_field_in_map(pointer_cast<Mark_field *>(arg), field);
  }
  bool check_function_as_value_generator(uchar *args) override {
    Check_function_as_value_generator_parameters *func_arg =
        pointer_cast<Check_function_as_value_generator_parameters *>(args);
    func_arg->banned_function_name = func_name();
    return true;
  }
  void cleanup() override {
    field = nullptr;
    Item_result_field::cleanup();
  }
};

/**
  Common abstract class for:
    Item_avg_field
    Item_variance_field
*/
class Item_sum_num_field : public Item_sum_hybrid_field {
 public:
  longlong val_int() override {
    /* can't be fix_fields()ed */
    return llrint_with_overflow_check(val_real());
  }
  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
    return get_date_from_numeric(ltime, fuzzydate); /* Decimal or real */
  }
  bool get_time(MYSQL_TIME *ltime) override {
    return get_time_from_numeric(ltime); /* Decimal or real */
  }
  bool is_null() override { return update_null_value() || null_value; }
};

class Item_avg_field : public Item_sum_num_field {
 public:
  uint f_precision, f_scale, dec_bin_size;
  uint prec_increment;
  Item_avg_field(Item_result res_type, Item_sum_avg *item);
  enum Type type() const override { return FIELD_AVG_ITEM; }
  double val_real() override;
  my_decimal *val_decimal(my_decimal *) override;
  String *val_str(String *) override;
  bool resolve_type(THD *) override { return false; }
  const char *func_name() const override {
    assert(0);
    return "avg_field";
  }
};

/// This is used in connection with an Item_sum_bit, @see Item_sum_hybrid_field
class Item_sum_bit_field : public Item_sum_hybrid_field {
 protected:
  ulonglong reset_bits;

 public:
  Item_sum_bit_field(Item_result res_type, Item_sum_bit *item,
                     ulonglong reset_bits);
  longlong val_int() override;
  double val_real() override;
  my_decimal *val_decimal(my_decimal *) override;
  String *val_str(String *) override;
  bool resolve_type(THD *) override { return false; }
  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
  bool get_time(MYSQL_TIME *ltime) override;
  enum Type type() const override { return FIELD_BIT_ITEM; }
  const char *func_name() const override {
    assert(0);
    return "sum_bit_field";
  }
};

/// Common abstraction for Item_sum_json_array and Item_sum_json_object
class Item_sum_json : public Item_sum {
  typedef Item_sum super;

 protected:
  /// String used when reading JSON binary values or JSON text values.
  String m_value;
  /// String used for converting JSON text values to utf8mb4 charset.
  String m_conversion_buffer;
  /// Wrapper around the container (object/array) which accumulates the value.
  unique_ptr_destroy_only<Json_wrapper> m_wrapper;

  /**
    Construct an Item_sum_json instance.

    @param wrapper a wrapper around the Json_array or Json_object that contains
                   the aggregated result
    @param parent_args arguments to forward to Item_sum's constructor
  */
  template <typename... Args>
  explicit Item_sum_json(unique_ptr_destroy_only<Json_wrapper> wrapper,
                         Args &&...parent_args);

 public:
  ~Item_sum_json() override;
  bool fix_fields(THD *thd, Item **pItem) override;
  enum Sumfunctype sum_func() const override { return JSON_AGG_FUNC; }
  Item_result result_type() const override { return STRING_RESULT; }

  double val_real() override;
  longlong val_int() override;
  String *val_str(String *str) override;
  bool val_json(Json_wrapper *wr) override;
  my_decimal *val_decimal(my_decimal *decimal_buffer) override;
  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
  bool get_time(MYSQL_TIME *ltime) override;

  void reset_field() override;
  void update_field() override;

  bool check_wf_semantics1(THD *, Query_block *,
                           Window_evaluation_requirements *) override;
};

/// Implements aggregation of values into an array.
class Item_sum_json_array final : public Item_sum_json {
  /// Accumulates the final value.
  unique_ptr_destroy_only<Json_array> m_json_array;

 public:
  Item_sum_json_array(THD *thd, Item_sum *item,
                      unique_ptr_destroy_only<Json_wrapper> wrapper,
                      unique_ptr_destroy_only<Json_array> array);
  Item_sum_json_array(const POS &pos, Item *a, PT_window *w,
                      unique_ptr_destroy_only<Json_wrapper> wrapper,
                      unique_ptr_destroy_only<Json_array> array);
  ~Item_sum_json_array() override;
  const char *func_name() const override { return "json_arrayagg"; }
  void clear() override;
  bool add() override;
  Item *copy_or_same(THD *thd) override;
};

/// Implements aggregation of values into an object.
class Item_sum_json_object final : public Item_sum_json {
  /// Accumulates the final value.
  unique_ptr_destroy_only<Json_object> m_json_object;
  /// Buffer used to get the value of the key.
  String m_tmp_key_value;
  /**
     Map of keys in Json_object and the count for each key
     within a window frame. It is used in handling rows
     leaving a window frame when rows are not sorted
     according to the key in Json_object.
   */
  std::map<std::string, int> m_key_map;
  /**
    If window provides ordering on the key in Json_object,
    a key_map is not needed to handle rows leaving a window
    frame. In this case, process_buffered_windowing_record()
    will set flags when a key/value pair can be removed from
    the Json_object.
  */
  bool m_optimize{false};

 public:
  Item_sum_json_object(THD *thd, Item_sum *item,
                       unique_ptr_destroy_only<Json_wrapper> wrapper,
                       unique_ptr_destroy_only<Json_object> object);
  Item_sum_json_object(const POS &pos, Item *a, Item *b, PT_window *w,
                       unique_ptr_destroy_only<Json_wrapper> wrapper,
                       unique_ptr_destroy_only<Json_object> object);
  ~Item_sum_json_object() override;
  const char *func_name() const override { return "json_objectagg"; }
  void clear() override;
  bool add() override;
  Item *copy_or_same(THD *thd) override;
  bool check_wf_semantics1(THD *thd, Query_block *select,
                           Window_evaluation_requirements *reqs) override;
};

class Item_sum_avg final : public Item_sum_sum {
 public:
  uint prec_increment;
  uint f_precision, f_scale, dec_bin_size;
  typedef Item_sum_sum super;
  my_decimal m_avg_dec;
  double m_avg;

  Item_sum_avg(const POS &pos, Item *item_par, bool distinct, PT_window *w)
      : Item_sum_sum(pos, item_par, distinct, w) {}

  Item_sum_avg(THD *thd, Item_sum_avg *item)
      : Item_sum_sum(thd, item), prec_increment(item->prec_increment) {}

  bool resolve_type(THD *thd) override;
  enum Sumfunctype sum_func() const override {
    return has_with_distinct() ? AVG_DISTINCT_FUNC : AVG_FUNC;
  }
  void clear() override;
  bool add() override;
  double val_real() override;
  // In SPs we might force the "wrong" type with select into a declare variable
  longlong val_int() override { return llrint_with_overflow_check(val_real()); }
  my_decimal *val_decimal(my_decimal *) override;
  String *val_str(String *str) override;
  void reset_field() override;
  void update_field() override;
  Item *result_item(Field *) override {
    return new Item_avg_field(hybrid_type, this);
  }
  const char *func_name() const override { return "avg"; }
  Item *copy_or_same(THD *thd) override;
  Field *create_tmp_field(bool group, TABLE *table) override;
  void cleanup() override {
    m_count = 0;
    m_frame_null_count = 0;
    Item_sum_sum::cleanup();
  }
};

class Item_sum_variance;

class Item_variance_field : public Item_sum_num_field {
 protected:
  uint sample;

 public:
  Item_variance_field(Item_sum_variance *item);
  enum Type type() const override { return FIELD_VARIANCE_ITEM; }
  double val_real() override;
  String *val_str(String *str) override { return val_string_from_real(str); }
  my_decimal *val_decimal(my_decimal *dec_buf) override {
    return val_decimal_from_real(dec_buf);
  }
  bool resolve_type(THD *) override { return false; }
  const char *func_name() const override {
    assert(0);
    return "variance_field";
  }
  bool check_function_as_value_generator(uchar *args) override {
    Check_function_as_value_generator_parameters *func_arg =
        pointer_cast<Check_function_as_value_generator_parameters *>(args);
    func_arg->err_code = func_arg->get_unnamed_function_error_code();
    return true;
  }
};

/*
  variance(a) =

  =  sum (ai - avg(a))^2 / count(a) )
  =  sum (ai^2 - 2*ai*avg(a) + avg(a)^2) / count(a)
  =  (sum(ai^2) - sum(2*ai*avg(a)) + sum(avg(a)^2))/count(a) =
  =  (sum(ai^2) - 2*avg(a)*sum(a) + count(a)*avg(a)^2)/count(a) =
  =  (sum(ai^2) - 2*sum(a)*sum(a)/count(a) + count(a)*sum(a)^2/count(a)^2
  )/count(a) = =  (sum(ai^2) - 2*sum(a)^2/count(a) + sum(a)^2/count(a)
  )/count(a) = =  (sum(ai^2) - sum(a)^2/count(a))/count(a)

  But, this falls prey to catastrophic cancellation.
  Instead, we use recurrence formulas in Algorithm I mentoned below
  for group aggregates.

  Algorithm I:
  M_{1} = x_{1}, ~ M_{k} = M_{k-1} + (x_{k} - M_{k-1}) / k newline
  S_{1} = 0, ~ S_{k} = S_{k-1} + (x_{k} - M_{k-1}) times (x_{k} - M_{k}) newline
  for 2 <= k <= n newline
  ital variance = S_{n} / (n-1)

  For aggregate window functions algorithm I cannot be optimized for
  moving frames since M_{i} changes for every row. So we use the
  following algorithm.

  Algorithm II:

  K = 0
  n = 0
  ex = 0
  ex2 = 0

  def add_sample(x):
  if (n == 0):
  K = x
  n = n + 1
  ex += x - K
  ex2 += (x - K) * (x - K)

  def remove_sample(x):
  n = n - 1
  ex -= (x - K)
  ex2 -= (x - K) * (x - K)

  def variance():
  return (ex2 - (ex*ex)/n) / (n-1)

  This formula facilitates incremental computation enabling us to
  optimize in case of moving window frames. The optimized codepath is taken
  only when windowing_use_high_precision is set to false. By default,
  aggregate window functions take the non-optimized codepath.
  Note:
  Results could differ between optimized and non-optimized code path.
  Hence algorithm II is used only when user sets
  windowing_use_high_precision to false.
*/

class Item_sum_variance : public Item_sum_num {
  bool resolve_type(THD *) override;

 public:
  Item_result hybrid_type;
  /**
    Used in recurrence relation.
  */
  double recurrence_m{0.0};
  double recurrence_s{0.0};
  double recurrence_s2{0.0};
  ulonglong count;
  uint sample;
  uint prec_increment;
  /**
    If set, uses a algorithm II mentioned in the class description
    to calculate the variance which helps in optimizing windowing
    functions in presence of frames.
  */
  bool optimize;

  Item_sum_variance(const POS &pos, Item *item_par, uint sample_arg,
                    PT_window *w)
      : Item_sum_num(pos, item_par, w),
        hybrid_type(REAL_RESULT),
        count(0),
        sample(sample_arg),
        optimize(false) {}

  Item_sum_variance(THD *thd, Item_sum_variance *item);
  enum Sumfunctype sum_func() const override { return VARIANCE_FUNC; }
  void clear() override;
  bool add() override;
  double val_real() override;
  my_decimal *val_decimal(my_decimal *) override;
  void reset_field() override;
  void update_field() override;
  Item *result_item(Field *) override { return new Item_variance_field(this); }
  void no_rows_in_result() override {}
  const char *func_name() const override {
    return sample ? "var_samp" : "variance";
  }
  Item *copy_or_same(THD *thd) override;
  Field *create_tmp_field(bool group, TABLE *table) override;
  enum Item_result result_type() const override { return REAL_RESULT; }
  void cleanup() override {
    count = 0;
    Item_sum_num::cleanup();
  }
  bool check_wf_semantics1(THD *thd, Query_block *select,
                           Window_evaluation_requirements *reqs) override;
};

class Item_sum_std;

class Item_std_field final : public Item_variance_field {
 public:
  Item_std_field(Item_sum_std *item);
  enum Type type() const override { return FIELD_STD_ITEM; }
  double val_real() override;
  my_decimal *val_decimal(my_decimal *) override;
  enum Item_result result_type() const override { return REAL_RESULT; }
  const char *func_name() const override {
    assert(0);
    return "std_field";
  }
  bool check_function_as_value_generator(uchar *args) override {
    Check_function_as_value_generator_parameters *func_arg =
        pointer_cast<Check_function_as_value_generator_parameters *>(args);
    func_arg->err_code = func_arg->get_unnamed_function_error_code();
    return true;
  }
};

/*
   standard_deviation(a) = sqrt(variance(a))
*/

class Item_sum_std : public Item_sum_variance {
 public:
  Item_sum_std(const POS &pos, Item *item_par, uint sample_arg, PT_window *w)
      : Item_sum_variance(pos, item_par, sample_arg, w) {}

  Item_sum_std(THD *thd, Item_sum_std *item) : Item_sum_variance(thd, item) {}
  enum Sumfunctype sum_func() const override { return STD_FUNC; }
  double val_real() override;
  Item *result_item(Field *) override { return new Item_std_field(this); }
  const char *func_name() const override {
    return sample ? "stddev_samp" : "std";
  }
  Item *copy_or_same(THD *thd) override;
  enum Item_result result_type() const override { return REAL_RESULT; }
};

// This class is a string or number function depending on num_func
class Arg_comparator;

/**
  Abstract base class for the MIN and MAX aggregate functions.
*/
class Item_sum_hybrid : public Item_sum {
  typedef Item_sum super;

 private:
  /**
    Tells if this is the MIN function (true) or the MAX function (false).
  */
  const bool m_is_min;
  /*
    For window functions MIN/MAX with optimized code path, no comparisons
    are needed beyond NULL detection: MIN/MAX are then roughly equivalent to
    FIRST/LAST_VALUE. For this case, 'value' is the value of
    the window function a priori taken from args[0], while arg_cache is used to
    remember the value from the previous row. NULLs need a bit of careful
    treatment.
  */
  Item_cache *value, *arg_cache;
  Arg_comparator *cmp;
  Item_result hybrid_type;
  bool was_values;  // Set if we have found at least one row (for max/min only)
  /**
    Set to true if the window is ordered ascending.
  */
  bool m_nulls_first;
  /**
    Set to true when min/max can be optimized using window's ordering.
  */
  bool m_optimize;
  /**
    For min() - Set to true when results are ordered in ascending and
    false when descending.
    For max() - Set to true when results are ordered in descending and
    false when ascending.
    Valid only when m_optimize is true.
  */
  bool m_want_first;  ///< Want first non-null value, else last non_null value
  /**
    Execution state: keeps track if this is the first row in the frame
    when buffering is not needed.
    Valid only when m_optimize is true.
  */
  int64 m_cnt;

  /**
    Execution state: keeps track of at which row we saved a non-null last
    value.
  */
  int64 m_saved_last_value_at;

  /**
    This function implements the optimized version of retrieving min/max
    value. When we have "ordered ASC" results in a window, min will always
    be the first value in the result set (neglecting the NULL's) and max
    will always be the last value (or the other way around, if ordered DESC).
    It is based on the implementation of FIRST_VALUE/LAST_VALUE, except for
    the NULL handling.

    @return true if computation yielded a NULL or error
  */
  bool compute();

  /**
    MIN/MAX function setup.

    Setup cache/comparator of MIN/MAX functions. When called by the
    copy_or_same() function, the value_arg parameter contains the calculated
    value of the original MIN/MAX object, and it is saved in this object's
    cache.

    @param item       the argument of the MIN/MAX function
    @param value_arg  the calculated value of the MIN/MAX function
    @return false on success, true on error
  */
  bool setup_hybrid(Item *item, Item *value_arg);

  /** Create a clone of this object. */
  virtual Item_sum_hybrid *clone_hybrid(THD *thd) const = 0;

 protected:
  Item_sum_hybrid(Item *item_par, bool is_min)
      : Item_sum(item_par),
        m_is_min(is_min),
        value(nullptr),
        arg_cache(nullptr),
        cmp(nullptr),
        hybrid_type(INT_RESULT),
        was_values(true),
        m_nulls_first(false),
        m_optimize(false),
        m_want_first(false),
        m_cnt(0),
        m_saved_last_value_at(0) {
    collation.set(&my_charset_bin);
  }

  Item_sum_hybrid(const POS &pos, Item *item_par, bool is_min, PT_window *w)
      : Item_sum(pos, item_par, w),
        m_is_min(is_min),
        value(nullptr),
        arg_cache(nullptr),
        cmp(nullptr),
        hybrid_type(INT_RESULT),
        was_values(true),
        m_nulls_first(false),
        m_optimize(false),
        m_want_first(false),
        m_cnt(0),
        m_saved_last_value_at(0) {
    collation.set(&my_charset_bin);
  }

  Item_sum_hybrid(THD *thd, const Item_sum_hybrid *item)
      : Item_sum(thd, item),
        m_is_min(item->m_is_min),
        value(item->value),
        arg_cache(nullptr),
        hybrid_type(item->hybrid_type),
        was_values(item->was_values),
        m_nulls_first(item->m_nulls_first),
        m_optimize(item->m_optimize),
        m_want_first(item->m_want_first),
        m_cnt(item->m_cnt),
        m_saved_last_value_at(0) {}

 public:
  bool fix_fields(THD *, Item **) override;
  void clear() override;
  void update_after_wf_arguments_changed(THD *thd) override;
  void split_sum_func(THD *thd, Ref_item_array ref_item_array,
                      mem_root_deque<Item *> *fields) override;
  double val_real() override;
  longlong val_int() override;
  longlong val_time_temporal() override;
  longlong val_date_temporal() override;
  my_decimal *val_decimal(my_decimal *) override;
  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
  bool get_time(MYSQL_TIME *ltime) override;
  void reset_field() override;
  String *val_str(String *) override;
  bool val_json(Json_wrapper *wr) override;
  bool keep_field_type() const override { return true; }
  enum Item_result result_type() const override { return hybrid_type; }
  TYPELIB *get_typelib() const override {
    assert(sum_func() == MAX_FUNC || sum_func() == MIN_FUNC);
    return arguments()[0]->get_typelib();
  }
  void update_field() override;
  void cleanup() override;
  bool any_value() { return was_values; }
  void no_rows_in_result() override;
  Field *create_tmp_field(bool group, TABLE *table) override;
  bool uses_only_one_row() const override { return m_optimize; }
  bool add() override;
  Item *copy_or_same(THD *thd) override;
  bool check_wf_semantics1(THD *thd, Query_block *select,
                           Window_evaluation_requirements *r) override;

 private:
  /*
    These functions check if the value on the current row exceeds the maximum or
    minimum value seen so far, and update the current max/min stored in
    result_field, if needed.
  */
  void min_max_update_str_field();
  void min_max_update_temporal_field();
  void min_max_update_json_field();
  void min_max_update_real_field();
  void min_max_update_int_field();
  void min_max_update_decimal_field();
};

class Item_sum_min final : public Item_sum_hybrid {
 public:
  Item_sum_min(Item *item_par) : Item_sum_hybrid(item_par, true) {}
  Item_sum_min(const POS &pos, Item *item_par, PT_window *w)
      : Item_sum_hybrid(pos, item_par, true, w) {}
  Item_sum_min(THD *thd, const Item_sum_min *item)
      : Item_sum_hybrid(thd, item) {}
  enum Sumfunctype sum_func() const override { return MIN_FUNC; }
  const char *func_name() const override { return "min"; }

 private:
  Item_sum_min *clone_hybrid(THD *thd) const override;
};

class Item_sum_max final : public Item_sum_hybrid {
 public:
  Item_sum_max(Item *item_par) : Item_sum_hybrid(item_par, false) {}
  Item_sum_max(const POS &pos, Item *item_par, PT_window *w)
      : Item_sum_hybrid(pos, item_par, false, w) {}
  Item_sum_max(THD *thd, const Item_sum_max *item)
      : Item_sum_hybrid(thd, item) {}
  enum Sumfunctype sum_func() const override { return MAX_FUNC; }
  const char *func_name() const override { return "max"; }

 private:
  Item_sum_max *clone_hybrid(THD *thd) const override;
};

/**
  Base class used to implement BIT_AND, BIT_OR and BIT_XOR.

  Each of them is both a set function and a framing window function.
*/
class Item_sum_bit : public Item_sum {
  typedef Item_sum super;
  /// Stores the neutral element for function
  ulonglong reset_bits;
  /// Stores the result value for the INT_RESULT
  ulonglong bits;
  /// Stores the result value for the STRING_RESULT
  String value_buff;
  /// Stores the Item's result type. Can only be INT_RESULT or STRING_RESULT
  Item_result hybrid_type;
  /// Buffer used to avoid String allocation in the constructor
  const char initial_value_buff_storage[1] = {0};

  /**
    Execution state (windowing): this is for counting rows entering and leaving
    the window frame, see #m_frame_null_count.
   */
  ulonglong m_count;

  /**
    Execution state (windowing): this is for counting NULLs of rows entering
    and leaving the window frame, when we use optimized inverse-based
    computations. By comparison with m_count we can know how many non-NULLs are
    in the frame.
  */
  ulonglong m_frame_null_count;

  /**
    Execution state (windowing): Used for AND, OR to be able to invert window
    functions in optimized mode.

    For the optimized code path of BIT_XXX wfs, we keep track of the number of
    bit values (0's or 1's; see below) seen in a frame using a 64 bits counter
    pr bit. This lets us compute the value of OR by just inspecting:

       - the number of 1's in the previous frame
       - whether any removed row(s) is a 1
       - whether any added row(s) is a 1

    Similarly for AND, we keep track of the number of 0's seen for a particular
    bit. To do this trick we need a counter per bit position. This array holds
    these counters.

    Note that for XOR, the inverse operation is identical to the operation,
    so we don't need the above.
  */
  ulonglong *m_digit_cnt;
  /*
    Size of allocated array m_digit_cnt.
    The size is DIGIT_CNT_CARD (for integer types) or ::max_length * 8 for bit
    strings.
  */
  uint m_digit_cnt_card;

  static constexpr uint DIGIT_CNT_CARD = sizeof(ulonglong) * 8;

 protected:
  bool m_is_xor;  ///< true iff BIT_XOR

 public:
  Item_sum_bit(const POS &pos, Item *item_par, ulonglong reset_arg,
               PT_window *w)
      : Item_sum(pos, item_par, w),
        reset_bits(reset_arg),
        bits(reset_arg),
        value_buff(initial_value_buff_storage, 1, &my_charset_bin),
        m_count(0),
        m_frame_null_count(0),
        m_digit_cnt(nullptr),
        m_digit_cnt_card(0),
        m_is_xor(false) {}

  /// Copy constructor, used for executing subqueries with temporary tables
  Item_sum_bit(THD *thd, Item_sum_bit *item)
      : Item_sum(thd, item),
        reset_bits(item->reset_bits),
        bits(item->bits),
        value_buff(initial_value_buff_storage, 1, &my_charset_bin),
        hybrid_type(item->hybrid_type),
        m_count(item->m_count),
        m_frame_null_count(item->m_frame_null_count),
        m_digit_cnt(nullptr),
        m_digit_cnt_card(0),
        m_is_xor(item->m_is_xor) {
    /*
       This constructor should only be called during the Optimize stage.
       Asserting that the item was not evaluated yet.
    */
    assert(item->value_buff.length() == 1);
    assert(item->bits == item->reset_bits);
  }

  Item *result_item(Field *) override {
    return new Item_sum_bit_field(hybrid_type, this, reset_bits);
  }

  enum Sumfunctype sum_func() const override { return SUM_BIT_FUNC; }
  enum Item_result result_type() const override { return hybrid_type; }
  void clear() override;
  longlong val_int() override;
  double val_real() override;
  String *val_str(String *str) override;
  my_decimal *val_decimal(my_decimal *decimal_value) override;
  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
  bool get_time(MYSQL_TIME *ltime) override;
  void reset_field() override;
  void update_field() override;
  bool resolve_type(THD *) override;
  bool fix_fields(THD *thd, Item **ref) override;
  void cleanup() override {
    bits = reset_bits;
    // At end of one execution of statement, free buffer to reclaim memory:
    value_buff.set(initial_value_buff_storage, 1, &my_charset_bin);
    Item_sum::cleanup();
  }

  /**
    Common implementation of Item_sum_or::add, Item_sum_and:add
    and Item_sum_xor::add.
  */
  bool add() override;
  /// @returns true iff this is BIT_AND.
  inline bool is_and() const { return reset_bits != 0; }

 private:
  /**
    Accumulate the value of 's1' (if in string mode) or of 'b1' (if in integer
    mode). Updates 'value_buff' or 'bits'.

    @param s1  argument to accumulate
    @param b1  argument to accumulate

    @returns true if error
  */
  bool add_bits(const String *s1, ulonglong b1);

  /**
    For windowing: perform inverse aggregation. "De-accumulate" the value of
    's1' (if in string mode) or of 'b1' (if in integer mode). Updates
    'value_buff' or 'bits'.

    For BIT_XOR we simply apply XOR as it's its inverse operation. For BIT_OR
    and BIT_AND we do the rest below.

    For each bit in argument, decrement the corresponding bits's counter
    ('m_digit_cnt') for that bit as follows: for BIT_AND, decrement the
    counter if we see a zero in that bit; for BIT_OR decrement the counter if
    we see a 1 in that bit.  Next, update 'value_buff' or 'bits' using the
    resulting counters: for each bit, for BIT_AND, set bit if we have counter
    == 0, i.e. we have no zero bits for that bit in the frame (yet).  For
    BIT_OR, set bit if we have counter > 0, i.e. at least one row in the frame
    has that bit set.

    @param  s1  the bits to be inverted from the aggregate value
    @param  b1  the bits to be inverted from the aggregate value
  */
  void remove_bits(const String *s1, ulonglong b1);
};

class Item_sum_or final : public Item_sum_bit {
 public:
  Item_sum_or(const POS &pos, Item *item_par, PT_window *w)
      : Item_sum_bit(pos, item_par, 0LL, w) {}

  Item_sum_or(THD *thd, Item_sum_or *item) : Item_sum_bit(thd, item) {}
  const char *func_name() const override { return "bit_or"; }
  Item *copy_or_same(THD *thd) override;
};

class Item_sum_and final : public Item_sum_bit {
 public:
  Item_sum_and(const POS &pos, Item *item_par, PT_window *w)
      : Item_sum_bit(pos, item_par, ULLONG_MAX, w) {}

  Item_sum_and(THD *thd, Item_sum_and *item) : Item_sum_bit(thd, item) {}
  const char *func_name() const override { return "bit_and"; }
  Item *copy_or_same(THD *thd) override;
};

class Item_sum_xor final : public Item_sum_bit {
 public:
  Item_sum_xor(const POS &pos, Item *item_par, PT_window *w)
      : Item_sum_bit(pos, item_par, 0LL, w) {
    m_is_xor = true;
  }

  Item_sum_xor(THD *thd, Item_sum_xor *item) : Item_sum_bit(thd, item) {}
  const char *func_name() const override { return "bit_xor"; }
  Item *copy_or_same(THD *thd) override;
};

/*
  User defined aggregates
*/

class Item_udf_sum : public Item_sum {
  typedef Item_sum super;

 protected:
  udf_handler udf;

 public:
  Item_udf_sum(const POS &pos, udf_func *udf_arg, PT_item_list *opt_list)
      : Item_sum(pos, opt_list, nullptr), udf(udf_arg) {
    allow_group_via_temp_table = false;
  }
  Item_udf_sum(THD *thd, Item_udf_sum *item)
      : Item_sum(thd, item), udf(item->udf) {
    udf.m_original = false;
  }
  ~Item_udf_sum() override {
    if (udf.m_original && udf.is_initialized()) udf.free_handler();
  }

  bool itemize(Parse_context *pc, Item **res) override;
  const char *func_name() const override { return udf.name(); }
  bool fix_fields(THD *thd, Item **ref) override {
    assert(fixed == 0);

    if (init_sum_func_check(thd)) return true;

    fixed = true;
    if (udf.fix_fields(thd, this, this->arg_count, this->args)) return true;

    return check_sum_func(thd, ref);
  }
  enum Sumfunctype sum_func() const override { return UDF_SUM_FUNC; }

  void clear() override;
  bool add() override;
  void reset_field() override {}
  void update_field() override {}
  void cleanup() override;
  void print(const THD *thd, String *str,
             enum_query_type query_type) const override;
};

class Item_sum_udf_float final : public Item_udf_sum {
 public:
  Item_sum_udf_float(const POS &pos, udf_func *udf_arg, PT_item_list *opt_list)
      : Item_udf_sum(pos, udf_arg, opt_list) {}
  Item_sum_udf_float(THD *thd, Item_sum_udf_float *item)
      : Item_udf_sum(thd, item) {}
  longlong val_int() override {
    assert(fixed == 1);
    return (longlong)rint(Item_sum_udf_float::val_real());
  }
  double val_real() override;
  String *val_str(String *str) override;
  my_decimal *val_decimal(my_decimal *) override;
  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
    return get_date_from_real(ltime, fuzzydate);
  }
  bool get_time(MYSQL_TIME *ltime) override {
    return get_time_from_real(ltime);
  }
  bool resolve_type(THD *) override {
    set_data_type(MYSQL_TYPE_DOUBLE);
    fix_num_length_and_dec();
    return false;
  }
  Item *copy_or_same(THD *thd) override;
};

class Item_sum_udf_int final : public Item_udf_sum {
 public:
  Item_sum_udf_int(const POS &pos, udf_func *udf_arg, PT_item_list *opt_list)
      : Item_udf_sum(pos, udf_arg, opt_list) {}
  Item_sum_udf_int(THD *thd, Item_sum_udf_int *item)
      : Item_udf_sum(thd, item) {}
  longlong val_int() override;
  double val_real() override {
    assert(fixed == 1);
    return (double)Item_sum_udf_int::val_int();
  }
  String *val_str(String *str) override;
  my_decimal *val_decimal(my_decimal *) override;
  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
    return get_date_from_int(ltime, fuzzydate);
  }
  bool get_time(MYSQL_TIME *ltime) override { return get_time_from_int(ltime); }
  enum Item_result result_type() const override { return INT_RESULT; }
  bool resolve_type(THD *) override {
    set_data_type_longlong();
    return false;
  }
  Item *copy_or_same(THD *thd) override;
};

class Item_sum_udf_str final : public Item_udf_sum {
 public:
  Item_sum_udf_str(const POS &pos, udf_func *udf_arg, PT_item_list *opt_list)
      : Item_udf_sum(pos, udf_arg, opt_list) {}
  Item_sum_udf_str(THD *thd, Item_sum_udf_str *item)
      : Item_udf_sum(thd, item) {}
  String *val_str(String *) override;
  double val_real() override {
    int err_not_used;
    const char *end_not_used;
    String *res;
    res = val_str(&str_value);
    return res ? my_strntod(res->charset(), res->ptr(), res->length(),
                            &end_not_used, &err_not_used)
               : 0.0;
  }
  longlong val_int() override {
    int err_not_used;
    String *res;
    const CHARSET_INFO *cs;

    if (!(res = val_str(&str_value))) return 0; /* Null value */
    cs = res->charset();
    const char *end = res->ptr() + res->length();
    return cs->cset->strtoll10(cs, res->ptr(), &end, &err_not_used);
  }
  my_decimal *val_decimal(my_decimal *dec) override;
  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
    return get_date_from_string(ltime, fuzzydate);
  }
  bool get_time(MYSQL_TIME *ltime) override {
    return get_time_from_string(ltime);
  }
  enum Item_result result_type() const override { return STRING_RESULT; }
  bool resolve_type(THD *) override;
  Item *copy_or_same(THD *thd) override;
};

class Item_sum_udf_decimal final : public Item_udf_sum {
 public:
  Item_sum_udf_decimal(const POS &pos, udf_func *udf_arg,
                       PT_item_list *opt_list)
      : Item_udf_sum(pos, udf_arg, opt_list) {}
  Item_sum_udf_decimal(THD *thd, Item_sum_udf_decimal *item)
      : Item_udf_sum(thd, item) {}
  String *val_str(String *) override;
  double val_real() override;
  longlong val_int() override;
  my_decimal *val_decimal(my_decimal *) override;
  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
    return get_date_from_decimal(ltime, fuzzydate);
  }
  bool get_time(MYSQL_TIME *ltime) override {
    return get_time_from_decimal(ltime);
  }
  enum Item_result result_type() const override { return DECIMAL_RESULT; }
  bool resolve_type(THD *) override {
    set_data_type(MYSQL_TYPE_NEWDECIMAL);
    fix_num_length_and_dec();
    return false;
  }
  Item *copy_or_same(THD *thd) override;
};

int group_concat_key_cmp_with_distinct(const void *arg, const void *key1,
                                       const void *key2);
int group_concat_key_cmp_with_order(const void *arg, const void *key1,
                                    const void *key2);
int dump_leaf_key(void *key_arg, element_count count [[maybe_unused]],
                  void *item_arg);

class Item_func_group_concat final : public Item_sum {
  typedef Item_sum super;

  /// True if GROUP CONCAT has the DISTINCT attribute
  bool distinct;
  /// The number of ORDER BY items.
  uint m_order_arg_count;
  /// The number of selected items, aka the concat field list
  uint m_field_arg_count;
  /// Resolver context, points to containing query block
  Name_resolution_context *context;
  /// String containing separator between group items
  String *separator;
  /// Describes the temporary table used to perform group concat
  Temp_table_param *tmp_table_param{nullptr};
  String result;
  TREE tree_base;
  TREE *tree{nullptr};

  /**
     If DISTINCT is used with this GROUP_CONCAT, this member is used to filter
     out duplicates.
     @see Item_func_group_concat::setup
     @see Item_func_group_concat::add
     @see Item_func_group_concat::clear
   */
  Unique *unique_filter{nullptr};
  /// Temporary table used to perform group concat
  TABLE *table{nullptr};
  Mem_root_array<ORDER> order_array;
  uint row_count{0};
  /**
    The maximum permitted result length in bytes as set in
    group_concat_max_len system variable
  */
  uint group_concat_max_len{0};
  bool warning_for_row{false};
  bool force_copy_fields{false};
  /// True if result has been written to output buffer.
  bool m_result_finalized{false};
  /**
    Following is 0 normal object and pointer to original one for copy
    (to correctly free resources)
  */
  Item_func_group_concat *original{nullptr};

  friend int group_concat_key_cmp_with_distinct(const void *arg,
                                                const void *key1,
                                                const void *key2);
  friend int group_concat_key_cmp_with_order(const void *arg, const void *key1,
                                             const void *key2);
  friend int dump_leaf_key(void *key_arg, element_count count [[maybe_unused]],
                           void *item_arg);

 public:
  Item_func_group_concat(const POS &pos, bool is_distinct,
                         PT_item_list *select_list,
                         PT_order_list *opt_order_list, String *separator,
                         PT_window *w);

  Item_func_group_concat(THD *thd, Item_func_group_concat *item);
  ~Item_func_group_concat() override {
    assert(original != nullptr || unique_filter == nullptr);
  }

  bool itemize(Parse_context *pc, Item **res) override;
  void cleanup() override;

  enum Sumfunctype sum_func() const override { return GROUP_CONCAT_FUNC; }
  const char *func_name() const override { return "group_concat"; }
  Item_result result_type() const override { return STRING_RESULT; }
  Field *make_string_field(TABLE *table_arg) const override;
  void clear() override;
  bool add() override;
  void reset_field() override { assert(0); }   // not used
  void update_field() override { assert(0); }  // not used
  bool fix_fields(THD *, Item **) override;
  bool setup(THD *thd) override;
  void make_unique() override;
  double val_real() override;
  longlong val_int() override {
    String *res;
    int error;
    if (!(res = val_str(&str_value))) return (longlong)0;
    const char *end_ptr = res->ptr() + res->length();
    return my_strtoll10(res->ptr(), &end_ptr, &error);
  }
  my_decimal *val_decimal(my_decimal *decimal_value) override {
    return val_decimal_from_string(decimal_value);
  }
  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
    return get_date_from_string(ltime, fuzzydate);
  }
  bool get_time(MYSQL_TIME *ltime) override {
    return get_time_from_string(ltime);
  }

  bool has_distinct() const noexcept { return distinct; }
  const String *get_separator_str() const noexcept { return separator; }
  uint32_t get_group_concat_max_len() const noexcept {
    return group_concat_max_len;
  }
  const Mem_root_array<ORDER> &get_order_array() const noexcept {
    return order_array;
  }

  String *val_str(String *str) override;
  Item *copy_or_same(THD *thd) override;
  void no_rows_in_result() override;
  void print(const THD *thd, String *str,
             enum_query_type query_type) const override;
  bool change_context_processor(uchar *arg) override {
    context = pointer_cast<Item_ident::Change_context *>(arg)->m_context;
    return false;
  }

  bool check_wf_semantics1(THD *, Query_block *,
                           Window_evaluation_requirements *) override {
    unsupported_as_wf();
    return true;
  }
};

/**
  Common parent class for window functions that always work on the entire
  partition, even if a frame is defined.

  The subclasses can be divided in two disjoint sub-categories:
     - one-pass
     - two-pass (requires partition cardinality to be evaluated)
  cf. method needs_partition_cardinality.
*/
class Item_non_framing_wf : public Item_sum {
  typedef Item_sum super;

 public:
  Item_non_framing_wf(const POS &pos, PT_window *w) : Item_sum(pos, w) {}
  Item_non_framing_wf(const POS &pos, Item *a, PT_window *w)
      : Item_sum(pos, a, w) {}
  Item_non_framing_wf(const POS &pos, PT_item_list *opt_list, PT_window *w)
      : Item_sum(pos, opt_list, w) {}
  Item_non_framing_wf(THD *thd, Item_non_framing_wf *i) : Item_sum(thd, i) {}

  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
    return get_date_from_numeric(ltime, fuzzydate);
  }

  bool get_time(MYSQL_TIME *ltime) override {
    return get_time_from_numeric(ltime);
  }

  void reset_field() override { assert(false); }
  void update_field() override { assert(false); }
  bool add() override {
    assert(false);
    return false;
  }

  bool fix_fields(THD *thd, Item **items) override;

  bool framing() const override { return false; }
};

/**
  ROW_NUMBER window function, cf. SQL 2003 Section 6.10 \<window function\>
*/
class Item_row_number : public Item_non_framing_wf {
  // Execution state variables
  ulonglong m_ctr;  ///< Increment for each row in partition

 public:
  Item_row_number(const POS &pos, PT_window *w)
      : Item_non_framing_wf(pos, w), m_ctr(0) {
    unsigned_flag = true;
  }

  const char *func_name() const override { return "row_number"; }
  enum Sumfunctype sum_func() const override { return ROW_NUMBER_FUNC; }

  bool resolve_type(THD *thd [[maybe_unused]]) override {
    set_data_type_longlong();
    return false;
  }

  longlong val_int() override;
  double val_real() override;
  my_decimal *val_decimal(my_decimal *buff) override;
  String *val_str(String *) override;

  void clear() override;

  Item_result result_type() const override { return INT_RESULT; }

  bool check_wf_semantics1(THD *, Query_block *,
                           Window_evaluation_requirements *) override {
    return false;
  }
};

/**
  RANK or DENSE_RANK window function, cf. SQL 2003 Section 6.10 \<window
  function\>
*/
class Item_rank : public Item_non_framing_wf {
  typedef Item_non_framing_wf super;
  bool m_dense;  ///< If true, the object represents DENSE_RANK
  // Execution state variables
  ulonglong m_rank_ctr;    ///< Increment when window order columns change
  ulonglong m_duplicates;  ///< Needed to make RANK different from DENSE_RANK
  Mem_root_array<Cached_item *>
      m_previous;  ///< Values of previous row's ORDER BY items
 public:
  Item_rank(const POS &pos, bool dense, PT_window *w)
      : Item_non_framing_wf(pos, w),
        m_dense(dense),
        m_rank_ctr(0),
        m_duplicates(0),
        m_previous(*THR_MALLOC) {
    unsigned_flag = true;
  }

  ~Item_rank() override;

  const char *func_name() const override {
    return m_dense ? "dense_rank" : "rank";
  }

  enum Sumfunctype sum_func() const override {
    return m_dense ? DENSE_RANK_FUNC : RANK_FUNC;
  }

  bool resolve_type(THD *thd [[maybe_unused]]) override {
    set_data_type_longlong();
    return false;
  }

  longlong val_int() override;
  double val_real() override;
  my_decimal *val_decimal(my_decimal *buff) override;
  String *val_str(String *) override;

  void update_after_wf_arguments_changed(THD *thd) override;
  bool check_wf_semantics1(THD *thd, Query_block *select,
                           Window_evaluation_requirements *reqs) override;
  /**
    Clear state for a new partition
  */
  void clear() override;
  Item_result result_type() const override { return INT_RESULT; }
};

/**
  CUME_DIST window function, cf. SQL 2003 Section 6.10 \<window function\>
*/
class Item_cume_dist : public Item_non_framing_wf {
  typedef Item_non_framing_wf super;

 public:
  Item_cume_dist(const POS &pos, PT_window *w) : Item_non_framing_wf(pos, w) {}

  const char *func_name() const override { return "cume_dist"; }
  enum Sumfunctype sum_func() const override { return CUME_DIST_FUNC; }

  bool resolve_type(THD *thd [[maybe_unused]]) override {
    set_data_type_double();
    return false;
  }

  bool check_wf_semantics1(THD *thd, Query_block *select,
                           Window_evaluation_requirements *reqs) override;

  bool needs_partition_cardinality() const override { return true; }
  void clear() override {}
  longlong val_int() override;
  double val_real() override;
  String *val_str(String *) override;
  my_decimal *val_decimal(my_decimal *buffer) override;
  Item_result result_type() const override { return REAL_RESULT; }
};

/**
  PERCENT_RANK window function, cf. SQL 2003 Section 6.10 \<window function\>
*/
class Item_percent_rank : public Item_non_framing_wf {
  typedef Item_non_framing_wf super;
  // Execution state variables
  ulonglong m_rank_ctr;  ///< Increment when window order columns change
  ulonglong m_peers;     ///< Needed to make PERCENT_RANK same for peers
  /**
    Set when the last peer has been visited. Needed to increment m_rank_ctr.
  */
  bool m_last_peer_visited;

 public:
  Item_percent_rank(const POS &pos, PT_window *w)
      : Item_non_framing_wf(pos, w),
        m_rank_ctr(0),
        m_peers(0),
        m_last_peer_visited(false) {}

  ~Item_percent_rank() override;
  const char *func_name() const override { return "percent_rank"; }
  enum Sumfunctype sum_func() const override { return PERCENT_RANK_FUNC; }

  bool resolve_type(THD *thd [[maybe_unused]]) override {
    set_data_type_double();
    return false;
  }

  bool check_wf_semantics1(THD *thd, Query_block *select,
                           Window_evaluation_requirements *reqs) override;
  bool needs_partition_cardinality() const override { return true; }

  void clear() override;
  longlong val_int() override;
  double val_real() override;
  String *val_str(String *) override;
  my_decimal *val_decimal(my_decimal *buffer) override;
  Item_result result_type() const override { return REAL_RESULT; }
};

/**
  NTILE window function, cf. SQL 2011 Section 6.10 \<window function\>
*/
class Item_ntile : public Item_non_framing_wf {
  typedef Item_non_framing_wf super;
  longlong m_value;

 public:
  Item_ntile(const POS &pos, Item *a, PT_window *w)
      : Item_non_framing_wf(pos, a, w), m_value(0) {
    unsigned_flag = true;
  }

  const char *func_name() const override { return "ntile"; }
  enum Sumfunctype sum_func() const override { return NTILE_FUNC; }

  bool resolve_type(THD *thd) override {
    if (args[0]->propagate_type(thd, MYSQL_TYPE_LONGLONG, true)) return true;
    set_data_type_longlong();
    return false;
  }

  bool fix_fields(THD *thd, Item **items) override;

  longlong val_int() override;
  double val_real() override;
  my_decimal *val_decimal(my_decimal *buff) override;
  String *val_str(String *) override;

  bool check_wf_semantics1(THD *thd, Query_block *select,
                           Window_evaluation_requirements *reqs) override;
  bool check_wf_semantics2(Window_evaluation_requirements *reqs) override;
  Item_result result_type() const override { return INT_RESULT; }
  void clear() override {}
  bool needs_partition_cardinality() const override { return true; }
};

/**
  LEAD/LAG window functions, cf. SQL 2011 Section 6.10 \<window function\>
*/
class Item_lead_lag : public Item_non_framing_wf {
  enum_null_treatment m_null_treatment;
  bool m_is_lead;  ///< if true, the function is LEAD, else LAG
  int64 m_n;       ///< canonicalized offset value
  Item_result m_hybrid_type;
  Item_cache *m_value;
  Item_cache *m_default;
  /**
    Execution state: if set, we already have a value for current row.
    State is used to avoid interference with other LEAD/LAG functions on
    the same window, since they share the same eval loop and they should
    trigger evaluation only when they are on the "right" row relative to
    current row. For other offsets, return NULL if we don't know the value
    for this function yet, or if we do (m_has_value==true), return the
    found value.
  */
  bool m_has_value;
  bool m_use_default;  ///< execution state: use default value for current row
  typedef Item_non_framing_wf super;

 public:
  Item_lead_lag(const POS &pos, bool lead,
                PT_item_list *opt_list,  // [0] expr, [1] offset, [2] default
                enum_null_treatment null_treatment, PT_window *w)
      : Item_non_framing_wf(pos, opt_list, w),
        m_null_treatment(null_treatment),
        m_is_lead(lead),
        m_n(0),
        m_hybrid_type(INVALID_RESULT),
        m_value(nullptr),
        m_default(nullptr),
        m_has_value(false),
        m_use_default(false) {}

  const char *func_name() const override {
    return (m_is_lead ? "lead" : "lag");
  }
  enum Sumfunctype sum_func() const override { return LEAD_LAG_FUNC; }

  bool resolve_type(THD *thd) override;
  bool fix_fields(THD *thd, Item **items) override;
  void update_after_wf_arguments_changed(THD *thd) override;
  void clear() override;
  bool check_wf_semantics1(THD *thd, Query_block *select,
                           Window_evaluation_requirements *reqs) override;
  bool check_wf_semantics2(Window_evaluation_requirements *reqs) override;
  enum Item_result result_type() const override { return m_hybrid_type; }

  longlong val_int() override;
  double val_real() override;
  String *val_str(String *str) override;
  my_decimal *val_decimal(my_decimal *decimal_buffer) override;

  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
  bool get_time(MYSQL_TIME *ltime) override;
  bool val_json(Json_wrapper *wr) override;

  bool needs_partition_cardinality() const override {
    /*
      A possible optimization here: if LAG, we are only interested in rows we
      have already seen, so we might compute the result without reading the
      entire partition as soon as we have the current row.  Similarly, a small
      LEAD value might avoid reading the entire partition also, giving shorter
      time to first result. For now, we read the entirely partition for these
      window functions - for simplicity.
    */
    return true;
  }

  void split_sum_func(THD *thd, Ref_item_array ref_item_array,
                      mem_root_deque<Item *> *fields) override;

  void set_has_value(bool value) { m_has_value = value; }
  bool has_value() const { return m_has_value; }

  void set_use_default(bool value) { m_use_default = value; }
  bool use_default() const { return m_use_default; }

 private:
  bool setup_lead_lag();
  /**
    Core logic of LEAD/LAG window functions

    @return true if computation yielded a NULL or error
  */
  bool compute();
};

/**
  FIRST_VALUE/LAST_VALUE window functions, cf. SQL 2011 Section 6.10 \<window
  function\>
*/
class Item_first_last_value : public Item_sum {
  bool m_is_first;  ///< if true, the function is FIRST_VALUE, else LAST_VALUE
  enum_null_treatment m_null_treatment;
  Item_result m_hybrid_type;
  Item_cache *m_value;
  int64 cnt;  ///< used when evaluating on-the-fly (non-buffered processing)
  typedef Item_sum super;

 public:
  Item_first_last_value(const POS &pos, bool first, Item *a,
                        enum_null_treatment null_treatment, PT_window *w)
      : Item_sum(pos, a, w),
        m_is_first(first),
        m_null_treatment(null_treatment),
        m_hybrid_type(INVALID_RESULT),
        m_value(nullptr),
        cnt(0) {}

  const char *func_name() const override {
    return m_is_first ? "first_value" : "last_value";
  }

  enum Sumfunctype sum_func() const override { return FIRST_LAST_VALUE_FUNC; }

  bool resolve_type(THD *thd) override;
  bool fix_fields(THD *thd, Item **items) override;
  void update_after_wf_arguments_changed(THD *thd) override;
  void clear() override;
  bool check_wf_semantics1(THD *thd, Query_block *select,
                           Window_evaluation_requirements *reqs) override;
  enum Item_result result_type() const override { return m_hybrid_type; }

  longlong val_int() override;
  double val_real() override;
  String *val_str(String *str) override;
  my_decimal *val_decimal(my_decimal *decimal_buffer) override;

  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
  bool get_time(MYSQL_TIME *ltime) override;
  bool val_json(Json_wrapper *wr) override;

  void reset_field() override { assert(false); }
  void update_field() override { assert(false); }
  bool add() override {
    assert(false);
    return false;
  }

  void split_sum_func(THD *thd, Ref_item_array ref_item_array,
                      mem_root_deque<Item *> *fields) override;
  bool uses_only_one_row() const override { return true; }

 private:
  bool setup_first_last();
  /**
    Core logic of FIRST/LAST_VALUE window functions

    @return true if computation yielded a NULL or error
  */
  bool compute();
};

/**
  NTH_VALUE window function, cf. SQL 2011 Section 6.10 \<window
  function\>
*/
class Item_nth_value : public Item_sum {
  enum_null_treatment m_null_treatment;
  int64 m_n;         ///< The N of the function
  bool m_from_last;  ///< true iff FROM_LAST was specified
  Item_result m_hybrid_type;
  enum_field_types m_hybrid_field_type;
  Item_cache *m_value;
  int64 m_cnt;  ///< used when evaluating on-the-fly (non-buffered processing)

  typedef Item_sum super;

 public:
  Item_nth_value(const POS &pos, PT_item_list *a, bool from_last,
                 enum_null_treatment null_treatment, PT_window *w)
      : Item_sum(pos, a, w),
        m_null_treatment(null_treatment),
        m_n(0),
        m_from_last(from_last),
        m_hybrid_type(INVALID_RESULT),
        m_value(nullptr),
        m_cnt(0) {}

  const char *func_name() const override { return "nth_value"; }
  enum Sumfunctype sum_func() const override { return NTH_VALUE_FUNC; }

  bool resolve_type(THD *thd) override;
  bool fix_fields(THD *thd, Item **items) override;
  void update_after_wf_arguments_changed(THD *thd) override;
  bool setup_nth();
  void clear() override;

  bool check_wf_semantics1(THD *thd, Query_block *select,
                           Window_evaluation_requirements *reqs) override;
  bool check_wf_semantics2(Window_evaluation_requirements *reqs) override;

  enum Item_result result_type() const override { return m_hybrid_type; }

  longlong val_int() override;
  double val_real() override;
  String *val_str(String *str) override;
  my_decimal *val_decimal(my_decimal *decimal_buffer) override;

  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
  bool get_time(MYSQL_TIME *ltime) override;
  bool val_json(Json_wrapper *wr) override;

  void reset_field() override { assert(false); }
  void update_field() override { assert(false); }
  bool add() override {
    assert(false);
    return false;
  }

  void split_sum_func(THD *thd, Ref_item_array ref_item_array,
                      mem_root_deque<Item *> *fields) override;
  bool uses_only_one_row() const override { return true; }

 private:
  /**
    Core logic of NTH_VALUE window functions

    @return true if computation yielded a NULL or error
  */
  bool compute();
};

/**
  Class for implementation of the GROUPING function. The GROUPING
  function distinguishes super-aggregate rows from regular grouped
  rows. GROUP BY extensions such as ROLLUP and CUBE produce
  super-aggregate rows where the set of all values is represented
  by null. Using the GROUPING function, you can distinguish a null
  representing the set of all values in a super-aggregate row from
  a NULL in a regular row.
*/
class Item_func_grouping : public Item_int_func {
 public:
  Item_func_grouping(const POS &pos, PT_item_list *a) : Item_int_func(pos, a) {
    set_grouping_func();
  }
  const char *func_name() const override { return "grouping"; }
  enum Functype functype() const override { return GROUPING_FUNC; }
  longlong val_int() override;
  bool aggregate_check_group(uchar *arg) override;
  bool fix_fields(THD *thd, Item **ref) override;
  void update_used_tables() override;
  bool aggregate_check_distinct(uchar *arg) override;
};

/**
  A wrapper Item that contains a number of aggregate items, one for each level
  of rollup (see Item_rollup_group_item for numbering conventions). When
  aggregating, every aggregator is either reset or updated as per the correct
  level, and when returning a value, the correct child item corresponding to
  the current rollup level is queried.
 */
class Item_rollup_sum_switcher final : public Item_sum {
 public:
  explicit Item_rollup_sum_switcher(List<Item> *sum_func_per_level)
      : Item_sum((*sum_func_per_level)[0]),
        m_num_levels(sum_func_per_level->size()) {
    args = (*THR_MALLOC)->ArrayAlloc<Item *>(sum_func_per_level->size());
    int i = 0;
    for (Item &item : *sum_func_per_level) {
      args[i++] = &item;
    }
    item_name = master()->item_name;
    base_query_block = master()->base_query_block;
    aggr_query_block = master()->aggr_query_block;
    hidden = master()->hidden;
    set_nullable(master()->is_nullable());
    set_distinct(master()->has_with_distinct());
    set_data_type_from_item(master());
  }
  double val_real() override;
  longlong val_int() override;
  String *val_str(String *str) override;
  my_decimal *val_decimal(my_decimal *dec) override;
  bool val_json(Json_wrapper *result) override;
  bool is_null() override;
  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
  bool get_time(MYSQL_TIME *ltime) override;
  const char *func_name() const override { return "rollup_sum_switcher"; }
  table_map used_tables() const override { return master()->used_tables(); }
  Item_result result_type() const override { return master()->result_type(); }
  bool resolve_type(THD *) override {
    set_data_type_from_item(master());
    return false;
  }
  void print(const THD *thd, String *str,
             enum_query_type query_type) const override;
  Field *create_tmp_field(bool group, TABLE *table) override;

  enum Sumfunctype sum_func() const override { return master()->sum_func(); }
  enum Sumfunctype real_sum_func() const override {
    return ROLLUP_SUM_SWITCHER_FUNC;
  }
  void reset_field() override { assert(false); }
  void update_field() override { assert(false); }
  void clear() override;
  bool add() override {
    assert(false);
    return true;
  }

  bool reset_and_add_for_rollup(int last_unchanged_group_item_idx);

  int set_aggregator(Aggregator::Aggregator_type aggregator) override;
  bool aggregator_setup(THD *thd) override;
  inline bool aggregator_add_all() {
    for (int i = 0; i < m_num_levels; ++i) {
      if (child(i)->aggregator_add()) {
        return true;
      }
    }
    return false;
  }

  // Used when create_tmp_table() needs to delay application of aggregate
  // functions to a later stage in the query processing.
  Item *get_arg(uint i) override { return master()->get_arg(i); }
  const Item *get_arg(uint i) const override { return master()->get_arg(i); }
  Item *set_arg(THD *thd, uint i, Item *new_val) override {
    Item *ret = nullptr;
    for (int j = 0; j < m_num_levels; ++j) {
      ret = child(j)->set_arg(thd, i, new_val);
    }
    return ret;  // Return the last one, arbitrarily.
  }
  uint argument_count() const override { return master()->argument_count(); }

  // Used by AggregateIterator.
  void set_current_rollup_level(int level) { m_current_rollup_level = level; }
  inline Item_sum *master() const { return child(0); }

  bool is_rollup_sum_wrapper() const override { return true; }
  const Item_sum *unwrap_sum() const override { return master(); }
  Item_sum *unwrap_sum() override { return master(); }

 private:
  inline Item *current_arg() const;
  inline Item_sum *child(size_t i) const {
    return down_cast<Item_sum *>(args[i]);
  }

  const int m_num_levels;
  int m_current_rollup_level = INT_MAX;
};
/// Implements ST_Collect which aggregates geometries into Multipoints,
/// Multilinestrings, Multipolygons and Geometrycollections.

class Item_sum_collect : public Item_sum {
 private:
  std::optional<gis::srid_t> srid;
  std::unique_ptr<gis::Geometrycollection> m_geometrycollection;
  void pop_front();

 public:
  using Super = Item_sum;
  Item_sum_collect(THD *thd, Item_sum *item) : Item_sum(thd, item) {
    set_data_type_geometry();
  }
  Item_sum_collect(const POS &pos, Item *a, PT_window *w, bool distinct)
      : Item_sum(pos, a, w) {
    set_distinct(distinct);
    set_data_type_geometry();
  }

  my_decimal *val_decimal(my_decimal *decimal_buffer) override;
  longlong val_int() override { return val_int_from_string(); }
  double val_real() override { return val_real_from_string(); }
  bool get_date(MYSQL_TIME *, my_time_flags_t) override { return true; }
  bool get_time(MYSQL_TIME *) override { return true; }
  enum Sumfunctype sum_func() const override { return GEOMETRY_AGGREGATE_FUNC; }
  Item_result result_type() const override { return STRING_RESULT; }
  int set_aggregator(Aggregator::Aggregator_type) override {
    /*
       In contrast to Item_sum, Item_sum_collect always uses Aggregator_simple,
       and only needs to reset its aggregator when called.
       */
    if (aggr) {
      aggr->clear();
      return false;
    }

    destroy(aggr);
    aggr = new (*THR_MALLOC) Aggregator_simple(this);
    return aggr ? false : true;
  }

  bool fix_fields(THD *thd, Item **ref) override;
  /*
     We need to override check_wf_semantics1 because it reports an error when
     with_distinct is set.
     */
  bool check_wf_semantics1(THD *thd, Query_block *,
                           Window_evaluation_requirements *r) override;

  Item *copy_or_same(THD *thd) override;

  void update_field() override;
  void reset_field() override;

  String *val_str(String *str) override;

  bool add() override;

  void read_result_field();
  void store_result_field();

  void clear() override;
  const char *func_name() const override { return "st_collect"; }
};

#endif /* ITEM_SUM_INCLUDED */