summaryrefslogtreecommitdiffstats
path: root/sql/sql_window.cc
blob: 8fe2890d536082b252f4fbf0177e6cf11a6fdd90 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
/*
   Copyright (c) 2016, 2022 MariaDB

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

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

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

#include "mariadb.h"
#include "sql_parse.h"
#include "sql_select.h"
#include "sql_list.h"
#include "item_windowfunc.h"
#include "filesort.h"
#include "sql_base.h"
#include "sql_window.h"


bool
Window_spec::check_window_names(List_iterator_fast<Window_spec> &it)
{
  if (window_names_are_checked)
    return false;
  const char *name= this->name();
  const char *ref_name= window_reference();
  it.rewind();
  Window_spec *win_spec;
  while((win_spec= it++) && win_spec != this)
  {
    const char *win_spec_name= win_spec->name();
    if (!win_spec_name)
      break;
    if (name && my_strcasecmp(system_charset_info, name, win_spec_name) == 0)
    {
      my_error(ER_DUP_WINDOW_NAME, MYF(0), name);
      return true;
    }
    if (ref_name &&
        my_strcasecmp(system_charset_info, ref_name, win_spec_name) == 0)
    {
      if (partition_list->elements)
      {
        my_error(ER_PARTITION_LIST_IN_REFERENCING_WINDOW_SPEC, MYF(0),
                 ref_name);
        return true;
      }
      if (win_spec->order_list->elements && order_list->elements)
      {
        my_error(ER_ORDER_LIST_IN_REFERENCING_WINDOW_SPEC, MYF(0), ref_name);
        return true;
      } 
      if (win_spec->window_frame)
      {
        my_error(ER_WINDOW_FRAME_IN_REFERENCED_WINDOW_SPEC, MYF(0), ref_name);
        return true;
      }
      referenced_win_spec= win_spec;
      if (partition_list->elements == 0)
        partition_list= win_spec->partition_list;
      if (order_list->elements == 0)
        order_list= win_spec->order_list;
    }
  }
  if (ref_name && !referenced_win_spec)
  {
    my_error(ER_WRONG_WINDOW_SPEC_NAME, MYF(0), ref_name);
    return true;
  }
  window_names_are_checked= true;
  return false;
}

void
Window_spec::print(String *str, enum_query_type query_type)
{
  str->append('(');
  print_partition(str, query_type);
  print_order(str, query_type);

  if (window_frame)
    window_frame->print(str, query_type);
  str->append(')');
}

void
Window_spec::print_partition(String *str, enum_query_type query_type)
{
  if (partition_list->first)
  {
    str->append(STRING_WITH_LEN(" partition by "));
    st_select_lex::print_order(str, partition_list->first, query_type);
  }
}

void
Window_spec::print_order(String *str, enum_query_type query_type)
{
  if (order_list->first)
  {
    str->append(STRING_WITH_LEN(" order by "));
    st_select_lex::print_order(str, order_list->first, query_type);
  }
}

bool
Window_frame::check_frame_bounds()
{
  if ((top_bound->is_unbounded() &&
       top_bound->precedence_type == Window_frame_bound::FOLLOWING) ||
      (bottom_bound->is_unbounded() &&
       bottom_bound->precedence_type == Window_frame_bound::PRECEDING) ||
      (top_bound->precedence_type == Window_frame_bound::CURRENT &&
       bottom_bound->precedence_type == Window_frame_bound::PRECEDING) ||
      (bottom_bound->precedence_type == Window_frame_bound::CURRENT &&
       top_bound->precedence_type == Window_frame_bound::FOLLOWING))
  {
    my_error(ER_BAD_COMBINATION_OF_WINDOW_FRAME_BOUND_SPECS, MYF(0));
    return true;
  }

  return false;
}


void
Window_frame::print(String *str, enum_query_type query_type)
{
  switch (units) {
  case UNITS_ROWS:
    str->append(STRING_WITH_LEN(" rows "));
    break;
  case UNITS_RANGE:
    str->append(STRING_WITH_LEN(" range "));
    break; 
  default:
    DBUG_ASSERT(0);
  }

  str->append(STRING_WITH_LEN("between "));
  top_bound->print(str, query_type);
  str->append(STRING_WITH_LEN(" and "));
  bottom_bound->print(str, query_type);
 
  if (exclusion != EXCL_NONE)
  {
     str->append(STRING_WITH_LEN(" exclude ")); 
     switch (exclusion) {
     case EXCL_CURRENT_ROW: 
       str->append(STRING_WITH_LEN(" current row "));
       break;
     case EXCL_GROUP: 
       str->append(STRING_WITH_LEN(" group "));
       break;
     case EXCL_TIES: 
       str->append(STRING_WITH_LEN(" ties "));
       break;
     default: 
       DBUG_ASSERT(0);
       ;
     }
  } 
}


void
Window_frame_bound::print(String *str, enum_query_type query_type)
{
  if (precedence_type == CURRENT)
  {
    str->append(STRING_WITH_LEN(" current row "));
    return;
  }
  if (is_unbounded())
    str->append(STRING_WITH_LEN(" unbounded "));
  else
    offset->print(str ,query_type);  
  switch (precedence_type) {
  case PRECEDING:
    str->append(STRING_WITH_LEN(" preceding "));
    break;
  case FOLLOWING:
    str->append(STRING_WITH_LEN(" following "));
    break;
  default:
    DBUG_ASSERT(0);
  }
}

/*
  Setup window functions in a select
*/

int
setup_windows(THD *thd, Ref_ptr_array ref_pointer_array, TABLE_LIST *tables,
              List<Item> &fields, List<Item> &all_fields,
              List<Window_spec> &win_specs, List<Item_window_func> &win_funcs)
{
  Window_spec *win_spec;
  DBUG_ENTER("setup_windows");
  List_iterator<Window_spec> it(win_specs);

  if (!thd->lex->current_select->is_win_spec_list_built)
  {

    /*
      Move all unnamed specifications after the named ones.
      We could have avoided it if we had built two separate lists for
      named and unnamed specifications.
    */
    Query_arena *arena, backup;
    arena= thd->activate_stmt_arena_if_needed(&backup);
    uint i = 0;
    uint elems= win_specs.elements;
    while ((win_spec= it++) && i++ < elems)
    {
      if (win_spec->name() == NULL)
      {
        it.remove();
        win_specs.push_back(win_spec);
      }
    }
    if (arena)
      thd->restore_active_arena(arena, &backup);

    it.rewind();

    thd->lex->current_select->is_win_spec_list_built= true;
  }

  List_iterator_fast<Window_spec> itp(win_specs);

  while ((win_spec= it++))
  {
    bool hidden_group_fields;
    if (win_spec->check_window_names(itp) ||
        setup_group(thd, ref_pointer_array, tables, fields, all_fields,
                    win_spec->partition_list->first, &hidden_group_fields,
                    true) ||
        setup_order(thd, ref_pointer_array, tables, fields, all_fields,
                    win_spec->order_list->first, true) ||
        (win_spec->window_frame && 
         win_spec->window_frame->check_frame_bounds()))
    {
      DBUG_RETURN(1);
    }

    if (win_spec->window_frame &&
        win_spec->window_frame->exclusion != Window_frame::EXCL_NONE)
    {
      my_error(ER_FRAME_EXCLUSION_NOT_SUPPORTED, MYF(0));
      DBUG_RETURN(1);
    }
    /*
       For  "win_func() OVER (ORDER BY order_list RANGE BETWEEN ...)",
       - ORDER BY order_list must not be ommitted
       - the list must have a single element.
    */
    if (win_spec->window_frame && 
        win_spec->window_frame->units == Window_frame::UNITS_RANGE)
    {
      if (win_spec->order_list->elements != 1)
      {
        my_error(ER_RANGE_FRAME_NEEDS_SIMPLE_ORDERBY, MYF(0));
        DBUG_RETURN(1);
      }

      /*
        "The declared type of SK shall be numeric, datetime, or interval"
        we don't support datetime or interval, yet.
      */
      Item_result rtype= win_spec->order_list->first->item[0]->result_type();
      if (rtype != REAL_RESULT && rtype != INT_RESULT && 
          rtype != DECIMAL_RESULT)
      {
        my_error(ER_WRONG_TYPE_FOR_RANGE_FRAME, MYF(0));
        DBUG_RETURN(1);
      }

      /*
        "The declared type of UVS shall be numeric if the declared type of SK 
        is numeric; otherwise, it shall be an interval type that may be added
        to or subtracted from the declared type of SK"
      */
      Window_frame_bound *bounds[]= {win_spec->window_frame->top_bound,
                                     win_spec->window_frame->bottom_bound,
                                     NULL};
      for (Window_frame_bound **pbound= &bounds[0]; *pbound; pbound++)
      {
        if (!(*pbound)->is_unbounded() &&
            ((*pbound)->precedence_type == Window_frame_bound::FOLLOWING ||
             (*pbound)->precedence_type == Window_frame_bound::PRECEDING))
        {
          Item_result rtype= (*pbound)->offset->result_type();
          if (rtype != REAL_RESULT && rtype != INT_RESULT && 
              rtype != DECIMAL_RESULT)
          {
            my_error(ER_WRONG_TYPE_FOR_RANGE_FRAME, MYF(0));
            DBUG_RETURN(1);
          }
        }
      }
    }

    /* "ROWS PRECEDING|FOLLOWING $n" must have a numeric $n */
    if (win_spec->window_frame && 
        win_spec->window_frame->units == Window_frame::UNITS_ROWS)
    {
      Window_frame_bound *bounds[]= {win_spec->window_frame->top_bound,
                                     win_spec->window_frame->bottom_bound,
                                     NULL};
      for (Window_frame_bound **pbound= &bounds[0]; *pbound; pbound++)
      {
        if (!(*pbound)->is_unbounded() &&
            ((*pbound)->precedence_type == Window_frame_bound::FOLLOWING ||
             (*pbound)->precedence_type == Window_frame_bound::PRECEDING))
        {
          Item *offset= (*pbound)->offset;
          if (offset->result_type() != INT_RESULT)
          {
            my_error(ER_WRONG_TYPE_FOR_ROWS_FRAME, MYF(0));
            DBUG_RETURN(1);
          }
        }
      }
    }
  }

  List_iterator_fast<Item_window_func> li(win_funcs);
  while (Item_window_func * win_func_item= li++)
  {
    if (win_func_item->check_result_type_of_order_item())
      DBUG_RETURN(1);
  }
  DBUG_RETURN(0);
}


/**
  @brief
  Find fields common for all partition lists used in window functions

  @param thd       The thread handle

  @details
   This function looks for the field references in the partition lists
   of all window functions used in this select that are common for
   all the partition lists. The function returns an ORDER list contained
   all such references.The list either is specially built by the function
   or is taken directly from the first window specification.

  @retval
    pointer to the first element of the ORDER list contained field
    references common for all partition lists
    0 if no such reference is found.
*/

ORDER *st_select_lex::find_common_window_func_partition_fields(THD *thd)
{
  ORDER *ord;
  Item *item;
  DBUG_ASSERT(window_funcs.elements);
  List_iterator_fast<Item_window_func> it(window_funcs);
  Item_window_func *first_wf= it++;
  if (!first_wf->window_spec->partition_list)
    return 0;
  List<Item> common_fields;
  uint first_partition_elements= 0;
  for (ord= first_wf->window_spec->partition_list->first; ord; ord= ord->next)
  {
    if ((*ord->item)->real_item()->type() == Item::FIELD_ITEM)
      common_fields.push_back(*ord->item, thd->mem_root);
    first_partition_elements++;
  }
  if (window_specs.elements == 1 &&
      common_fields.elements == first_partition_elements)
    return first_wf->window_spec->partition_list->first;
  List_iterator<Item> li(common_fields);
  Item_window_func *wf;
  while (common_fields.elements && (wf= it++))
  {
    if (!wf->window_spec->partition_list)
      return 0;
    while ((item= li++))
    {
      for (ord= wf->window_spec->partition_list->first; ord; ord= ord->next)
      {
        if (item->eq(*ord->item, false))
	  break;
      }
      if (!ord)
        li.remove();
    }
    li.rewind();
  }
  if (!common_fields.elements)
    return 0;
  if (common_fields.elements == first_partition_elements)
    return first_wf->window_spec->partition_list->first;
  SQL_I_List<ORDER> res_list;
  for (ord= first_wf->window_spec->partition_list->first, item= li++;
       ord; ord= ord->next)
  {
    if (item != *ord->item)
      continue;
    if (add_to_list(thd, res_list, item, ord->direction))
      return 0;
    item= li++;
  }
  return res_list.first;
}


/////////////////////////////////////////////////////////////////////////////
// Sorting window functions to minimize the number of table scans
// performed during the computation of these functions 
/////////////////////////////////////////////////////////////////////////////

#define CMP_LT        -2    // Less than
#define CMP_LT_C      -1    // Less than and compatible
#define CMP_EQ         0    // Equal to
#define CMP_GT_C       1    // Greater than and compatible
#define CMP_GT         2    // Greater then

static
int compare_order_elements(ORDER *ord1, int weight1,
                           ORDER *ord2, int weight2)
{
  if (*ord1->item == *ord2->item && ord1->direction == ord2->direction)
    return CMP_EQ;
  Item *item1= (*ord1->item)->real_item();
  Item *item2= (*ord2->item)->real_item();

  bool item1_field= (item1->type() == Item::FIELD_ITEM);
  bool item2_field= (item2->type() == Item::FIELD_ITEM);

  ptrdiff_t cmp;
  if (item1_field && item2_field)
  {
    DBUG_ASSERT(((Item_field *) item1)->field->table ==
                ((Item_field *) item2)->field->table);
    cmp= ((Item_field *) item1)->field->field_index -
         ((Item_field *) item2)->field->field_index;
  }
  else if (item1_field && !item2_field)
    return CMP_LT;
  else if (!item1_field && item2_field)
    return CMP_LT;
  else
  {
    /*
      Ok, item1_field==NULL and item2_field==NULL.
      We're not able to compare Item expressions. Order them according to
      their passed "weight" (which comes from Window_spec::win_spec_number):
    */
    if (weight1 != weight2)
      cmp= weight1 - weight2;
    else
    {
      /*
        The weight is the same. That is, the elements come from the same
        window specification... This shouldn't happen.
      */
      DBUG_ASSERT(0);
      cmp= item1 - item2;
    }
  }

  if (cmp == 0)
  {
    if (ord1->direction == ord2->direction)
      return CMP_EQ;
    return ord1->direction > ord2->direction ? CMP_GT : CMP_LT;
  }
  else
    return cmp > 0 ? CMP_GT : CMP_LT;
}

static
int compare_order_lists(SQL_I_List<ORDER> *part_list1,
                        int spec_number1,
                        SQL_I_List<ORDER> *part_list2,
                        int spec_number2)
{
  if (part_list1 == part_list2)
    return CMP_EQ;
  ORDER *elem1= part_list1->first;
  ORDER *elem2= part_list2->first;
  for ( ; elem1 && elem2; elem1= elem1->next, elem2= elem2->next)
  {
    int cmp;
    // remove all constants as we don't need them for comparision
    while(elem1 && ((*elem1->item)->real_item())->const_item())
    {
      elem1= elem1->next;
      continue;
    }

    while(elem2 && ((*elem2->item)->real_item())->const_item())
    {
      elem2= elem2->next;
      continue;
    }

    if (!elem1 || !elem2)
      break;

    if ((cmp= compare_order_elements(elem1, spec_number1,
                                     elem2, spec_number2)))
      return cmp;
  }
  if (elem1)
    return CMP_GT_C;
  if (elem2)
    return CMP_LT_C;
  return CMP_EQ;
}


static
int compare_window_frame_bounds(Window_frame_bound *win_frame_bound1,
                                Window_frame_bound *win_frame_bound2,
                                bool is_bottom_bound)
{ 
  int res;
  if (win_frame_bound1->precedence_type != win_frame_bound2->precedence_type)
  {
    res= win_frame_bound1->precedence_type > win_frame_bound2->precedence_type ?
         CMP_GT : CMP_LT;
    if (is_bottom_bound)
      res= -res;
    return res;
  }

  if (win_frame_bound1->is_unbounded() && win_frame_bound2->is_unbounded())
    return CMP_EQ;

  if (!win_frame_bound1->is_unbounded() && !win_frame_bound2->is_unbounded())
  { 
    if (win_frame_bound1->offset->eq(win_frame_bound2->offset, true))
      return CMP_EQ;
    else
    {
      res= strcmp(win_frame_bound1->offset->name.str,
                  win_frame_bound2->offset->name.str);
      res= res > 0 ? CMP_GT : CMP_LT;
      if (is_bottom_bound)
        res= -res;
      return res;
    }
  }

  /* 
    Here we have:
    win_frame_bound1->is_unbounded() != win_frame_bound1->is_unbounded()
  */
  return is_bottom_bound != win_frame_bound1->is_unbounded() ? CMP_LT : CMP_GT; 
}


static
int compare_window_frames(Window_frame *win_frame1,
                          Window_frame *win_frame2)
{
  int cmp;

  if (win_frame1 == win_frame2)
    return CMP_EQ;

  if (!win_frame1)
    return CMP_LT;

  if (!win_frame2)
    return CMP_GT;

  if (win_frame1->units != win_frame2->units)
    return win_frame1->units > win_frame2->units ? CMP_GT : CMP_LT;

  cmp= compare_window_frame_bounds(win_frame1->top_bound,
                                   win_frame2->top_bound,
                                   false);
  if (cmp)
    return cmp;

  cmp= compare_window_frame_bounds(win_frame1->bottom_bound,
                                   win_frame2->bottom_bound,
                                   true);  
  if (cmp)
    return cmp;

  if (win_frame1->exclusion != win_frame2->exclusion)
    return win_frame1->exclusion > win_frame2->exclusion ? CMP_GT_C : CMP_LT_C;

  return CMP_EQ;
}

static 
int compare_window_spec_joined_lists(Window_spec *win_spec1,
                                     Window_spec *win_spec2)
{
  win_spec1->join_partition_and_order_lists();
  win_spec2->join_partition_and_order_lists();
  int cmp= compare_order_lists(win_spec1->partition_list, 
                               win_spec1->win_spec_number,
                               win_spec2->partition_list,
                               win_spec2->win_spec_number);
  win_spec1->disjoin_partition_and_order_lists();
  win_spec2->disjoin_partition_and_order_lists();
  return cmp;
}


static
int compare_window_funcs_by_window_specs(Item_window_func *win_func1,
                                         Item_window_func *win_func2,
                                         void *arg)
{
  int cmp;
  Window_spec *win_spec1= win_func1->window_spec;
  Window_spec *win_spec2= win_func2->window_spec;
  if (win_spec1 == win_spec2)
    return CMP_EQ;
  cmp= compare_order_lists(win_spec1->partition_list, 
                           win_spec1->win_spec_number,
                           win_spec2->partition_list,
                           win_spec2->win_spec_number);
  if (cmp == CMP_EQ)
  {
    /* 
      Partition lists contain the same elements. 
      Let's use only one of the lists.
    */
    if (!win_spec1->name() && win_spec2->name())
    {
      win_spec1->save_partition_list= win_spec1->partition_list;
      win_spec1->partition_list= win_spec2->partition_list;
    }
    else
    {
      win_spec2->save_partition_list= win_spec2->partition_list;
      win_spec2->partition_list= win_spec1->partition_list;
    }

    cmp= compare_order_lists(win_spec1->order_list,
                             win_spec1->win_spec_number,
                             win_spec2->order_list,
                             win_spec2->win_spec_number);

    if (cmp != CMP_EQ)
      return cmp;

    /* 
       Order lists contain the same elements.
       Let's use only one of the lists.
    */
    if (!win_spec1->name() && win_spec2->name())
    {
      win_spec1->save_order_list= win_spec2->order_list;
      win_spec1->order_list= win_spec2->order_list;
    }
    else
    {
      win_spec1->save_order_list= win_spec2->order_list;
      win_spec2->order_list= win_spec1->order_list;
    }

    cmp= compare_window_frames(win_spec1->window_frame,
                               win_spec2->window_frame);

    if (cmp != CMP_EQ)
      return cmp;

    /* Window frames are equal. Let's use only one of them. */
    if (!win_spec1->name() && win_spec2->name())
      win_spec1->window_frame= win_spec2->window_frame;
    else
      win_spec2->window_frame= win_spec1->window_frame;

    return CMP_EQ;
  }
  
  if (cmp == CMP_GT || cmp == CMP_LT)
    return cmp;

  /* one of the partitions lists is the proper beginning of the another */
  cmp= compare_window_spec_joined_lists(win_spec1, win_spec2);

  if (CMP_LT_C <= cmp && cmp <= CMP_GT_C) 
    cmp= win_spec1->partition_list->elements <
      win_spec2->partition_list->elements ? CMP_GT_C : CMP_LT_C;

  return cmp;
}


typedef int (*Item_window_func_cmp)(Item_window_func *f1,
                                    Item_window_func *f2,
                                    void *arg); 
/*
  @brief
    Sort window functions so that those that can be computed together are
    adjacent.

  @detail
    Sort window functions by their
     - required sorting order,
     - partition list,
     - window frame compatibility.

    The changes between the groups are marked by setting item_window_func->marker.
*/

static
void order_window_funcs_by_window_specs(List<Item_window_func> *win_func_list)
{
  if (win_func_list->elements == 0)
    return;

  bubble_sort<Item_window_func>(win_func_list,
                                compare_window_funcs_by_window_specs,
                                NULL);

  List_iterator_fast<Item_window_func> it(*win_func_list);
  Item_window_func *prev= it++;
  prev->marker= (MARKER_SORTORDER_CHANGE |
                 MARKER_PARTITION_CHANGE |
                 MARKER_FRAME_CHANGE);
  Item_window_func *curr;
  while ((curr= it++))
  {
    Window_spec *win_spec_prev= prev->window_spec;
    Window_spec *win_spec_curr= curr->window_spec;
    curr->marker= MARKER_UNUSED;
    if (!(win_spec_prev->partition_list == win_spec_curr->partition_list &&
          win_spec_prev->order_list == win_spec_curr->order_list))
    {
      int cmp;
      if (win_spec_prev->partition_list == win_spec_curr->partition_list)
        cmp= compare_order_lists(win_spec_prev->order_list,
                                 win_spec_prev->win_spec_number,
                                 win_spec_curr->order_list,
                                 win_spec_curr->win_spec_number);
      else
        cmp= compare_window_spec_joined_lists(win_spec_prev, win_spec_curr);
      if (!(CMP_LT_C <= cmp && cmp <= CMP_GT_C))
      {
        curr->marker= (MARKER_SORTORDER_CHANGE |
                       MARKER_PARTITION_CHANGE |
                       MARKER_FRAME_CHANGE);
      }
      else if (win_spec_prev->partition_list != win_spec_curr->partition_list)
      {
        curr->marker|= MARKER_PARTITION_CHANGE | MARKER_FRAME_CHANGE;
      }
    }
    else if (win_spec_prev->window_frame != win_spec_curr->window_frame)
      curr->marker|= MARKER_FRAME_CHANGE;

    prev= curr;
  }
}


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


/////////////////////////////////////////////////////////////////////////////
// Window Frames support 
/////////////////////////////////////////////////////////////////////////////

// note: make rr_from_pointers static again when not need it here anymore
int rr_from_pointers(READ_RECORD *info);


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


/*
  A cursor over a sequence of rowids. One can
   - Move to next rowid
   - jump to given number in the sequence
   - Know the number of the current rowid (i.e. how many rowids have been read)
*/

class Rowid_seq_cursor
{
public:
  Rowid_seq_cursor() : io_cache(NULL), ref_buffer(0) {}
  virtual ~Rowid_seq_cursor()
  {
    if (ref_buffer)
      my_free(ref_buffer);
    if (io_cache)
    {
      end_slave_io_cache(io_cache);
      my_free(io_cache);
      io_cache= NULL;
    }
  }

private:
  /* Length of one rowid element */
  size_t ref_length;

  /* If io_cache=!NULL, use it */
  IO_CACHE *io_cache;
  uchar *ref_buffer;   /* Buffer for the last returned rowid */
  ha_rows rownum;     /* Number of the rowid that is about to be returned */
  ha_rows current_ref_buffer_rownum;
  bool ref_buffer_valid;

  /* The following are used when we are reading from an array of pointers */
  uchar *cache_start;
  uchar *cache_pos;
  uchar *cache_end;
public:

  void init(READ_RECORD *info)
  {
    ref_length= info->ref_length;
    if (info->read_record_func == rr_from_pointers)
    {
      io_cache= NULL;
      cache_start= info->cache_pos;
      cache_pos=   info->cache_pos;
      cache_end=   info->cache_end;
    }
    else
    {
      //DBUG_ASSERT(info->read_record == rr_from_tempfile);
      rownum= 0;
      io_cache= (IO_CACHE*)my_malloc(PSI_INSTRUMENT_ME, sizeof(IO_CACHE), MYF(0));
      init_slave_io_cache(info->io_cache, io_cache);

      ref_buffer= (uchar*)my_malloc(PSI_INSTRUMENT_ME, ref_length, MYF(0));
      ref_buffer_valid= false;
    }
  }

  virtual int next()
  {
    /* Allow multiple next() calls in EOF state. */
    if (at_eof())
        return -1;

    if (io_cache)
    {
      rownum++;
    }
    else
    {
      cache_pos+= ref_length;
      DBUG_ASSERT(cache_pos <= cache_end);
    }
    return 0;
  }

  virtual int prev()
  {
    if (io_cache)
    {
      if (rownum == 0)
        return -1;

      rownum--;
      return 0;
    }
    else
    {
      /* Allow multiple prev() calls when positioned at the start. */
      if (cache_pos == cache_start)
        return -1;
      cache_pos-= ref_length;
      DBUG_ASSERT(cache_pos >= cache_start);
      return 0;
    }
  }

  ha_rows get_rownum() const
  {
    if (io_cache)
      return rownum;
    else
      return (cache_pos - cache_start) / ref_length;
  }

  void move_to(ha_rows row_number)
  {
    if (io_cache)
    {
      rownum= row_number;
    }
    else
    {
      cache_pos= MY_MIN(cache_end, cache_start + row_number * ref_length);
      DBUG_ASSERT(cache_pos <= cache_end);
    }
  }

protected:
  bool at_eof()
  {
    if (io_cache)
    {
      return rownum * ref_length >= io_cache->end_of_file;
    }
    else
      return (cache_pos == cache_end);
  }

  bool get_curr_rowid(uchar **row_id)
  {
    if (io_cache)
    {
      DBUG_ASSERT(!at_eof());
      if (!ref_buffer_valid || current_ref_buffer_rownum != rownum)
      {
        seek_io_cache(io_cache, rownum * ref_length);
        if (my_b_read(io_cache,ref_buffer,ref_length))
        {
          /* Error reading from file. */
          return true;
        }
        ref_buffer_valid= true;
        current_ref_buffer_rownum = rownum;
      }
      *row_id = ref_buffer;
      return false;
    }
    else
    {
      *row_id= cache_pos;
      return false;
    }
  }
};


/*
  Cursor which reads from rowid sequence and also retrieves table rows.
*/

class Table_read_cursor : public Rowid_seq_cursor
{
public:
  virtual ~Table_read_cursor() = default;

  void init(READ_RECORD *info)
  {
    Rowid_seq_cursor::init(info);
    table= info->table;
    record= info->record();
  }

  virtual int fetch()
  {
    if (at_eof())
      return -1;

    uchar* curr_rowid;
    if (get_curr_rowid(&curr_rowid))
      return -1;
    return table->file->ha_rnd_pos(record, curr_rowid);
  }

private:
  /* The table that is acccesed by this cursor. */
  TABLE *table;
  /* Buffer where to store the table's record data. */
  uchar *record;

  // TODO(spetrunia): should move_to() also read row here?
};


/*
  A cursor which only moves within a partition. The scan stops at the partition
  end, and it needs an explicit command to move to the next partition.

  This cursor can not move backwards.
*/

class Partition_read_cursor : public Table_read_cursor
{
public:
  Partition_read_cursor(THD *thd, SQL_I_List<ORDER> *partition_list) :
    bound_tracker(thd, partition_list) {}

  void init(READ_RECORD *info)
  {
    Table_read_cursor::init(info);
    bound_tracker.init();
    end_of_partition= false;
  }

  /*
    Informs the cursor that we need to move into the next partition.
    The next partition is provided in two ways:
    - in table->record[0]..
    - rownum parameter has the row number.
  */
  void on_next_partition(ha_rows rownum)
  {
    /* Remember the sort key value from the new partition */
    move_to(rownum);
    bound_tracker.check_if_next_group();
    end_of_partition= false;

  }

  /*
    This returns -1 when end of partition was reached.
  */
  int next()
  {
    int res;
    if (end_of_partition)
      return -1;

    if ((res= Table_read_cursor::next()) ||
        (res= fetch()))
    {
      /* TODO(cvicentiu) This does not consider table read failures.
         Perhaps assuming end of table like this is fine in that case. */

      /* This row is the final row in the table. To maintain semantics
         that cursors always point to the last valid row, move back one step,
         but mark end_of_partition as true. */
      Table_read_cursor::prev();
      end_of_partition= true;
      return res;
    }

    if (bound_tracker.compare_with_cache())
    {
      /* This row is part of a new partition, don't move
         forward any more untill we get informed of a new partition. */
      Table_read_cursor::prev();
      end_of_partition= true;
      return -1;
    }
    return 0;
  }

private:
  Group_bound_tracker bound_tracker;
  bool end_of_partition;
};



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

/*
  Window frame bound cursor. Abstract interface.

  @detail
    The cursor moves within the partition that the current row is in.
    It may be ahead or behind the current row.

    The cursor also assumes that the current row moves forward through the
    partition and will move to the next adjacent partition after this one.

    List of all cursor classes:
      Frame_cursor
        Frame_range_n_top
        Frame_range_n_bottom

        Frame_range_current_row_top
        Frame_range_current_row_bottom

        Frame_n_rows_preceding
        Frame_n_rows_following

        Frame_rows_current_row_top = Frame_n_rows_preceding(0)
        Frame_rows_current_row_bottom

        // These handle both RANGE and ROWS-type bounds
        Frame_unbounded_preceding
        Frame_unbounded_following

        // This is not used as a frame bound, it counts rows in the partition:
        Frame_unbounded_following_set_count : public Frame_unbounded_following

  @todo
  - if we want to allocate this on the MEM_ROOT we should make sure 
    it is not re-allocated for every subquery execution.
*/

class Frame_cursor : public Sql_alloc
{
public:
  Frame_cursor() : sum_functions(), perform_no_action(false) {}

  virtual void init(READ_RECORD *info) {};

  bool add_sum_func(Item_sum* item)
  {
    return sum_functions.push_back(item);
  }
  /*
    Current row has moved to the next partition and is positioned on the first
    row there. Position the frame bound accordingly.

    @param first   -  TRUE means this is the first partition
    @param item    -  Put or remove rows from there.

    @detail
      - if first==false, the caller guarantees that tbl->record[0] points at the
        first row in the new partition.
      - if first==true, we are just starting in the first partition and no such
        guarantee is provided.

      - The callee may move tbl->file and tbl->record[0] to point to some other
        row.
  */
  virtual void pre_next_partition(ha_rows rownum) {};
  virtual void next_partition(ha_rows rownum)=0;

  /*
    The current row has moved one row forward.
    Move this frame bound accordingly, and update the value of aggregate
    function as necessary.
  */
  virtual void pre_next_row() {};
  virtual void next_row()=0;

  virtual bool is_outside_computation_bounds() const { return false; };

  virtual ~Frame_cursor() = default;

  /*
     Regular frame cursors add or remove values from the sum functions they
     manage. By calling this method, they will only perform the required
     movement within the table, but no adding/removing will happen.
  */
  void set_no_action()
  {
    perform_no_action= true;
  }

  /* Retrieves the row number that this cursor currently points at. */
  virtual ha_rows get_curr_rownum() const= 0;

protected:
  inline void add_value_to_items()
  {
    if (perform_no_action)
      return;

    List_iterator_fast<Item_sum> it(sum_functions);
    Item_sum *item_sum;
    while ((item_sum= it++))
    {
      item_sum->add();
    }
  }

  inline void remove_value_from_items()
  {
    if (perform_no_action)
      return;

    List_iterator_fast<Item_sum> it(sum_functions);
    Item_sum *item_sum;
    while ((item_sum= it++))
    {
      item_sum->remove();
    }
  }

  /* Clear all sum functions handled by this cursor. */
  void clear_sum_functions()
  {
    List_iterator_fast<Item_sum> iter_sum_func(sum_functions);
    Item_sum *sum_func;
    while ((sum_func= iter_sum_func++))
    {
      sum_func->clear();
    }
  }

  /* Sum functions that this cursor handles. */
  List<Item_sum> sum_functions;

private:
  bool perform_no_action;
};

/*
  A class that owns cursor objects associated with a specific window function.
*/
class Cursor_manager
{
public:
  bool add_cursor(Frame_cursor *cursor)
  {
    return cursors.push_back(cursor);
  }

  void initialize_cursors(READ_RECORD *info)
  {
    List_iterator_fast<Frame_cursor> iter(cursors);
    Frame_cursor *fc;
    while ((fc= iter++))
      fc->init(info);
  }

  void notify_cursors_partition_changed(ha_rows rownum)
  {
    List_iterator_fast<Frame_cursor> iter(cursors);
    Frame_cursor *cursor;
    while ((cursor= iter++))
      cursor->pre_next_partition(rownum);

    iter.rewind();
    while ((cursor= iter++))
      cursor->next_partition(rownum);
  }

  void notify_cursors_next_row()
  {
    List_iterator_fast<Frame_cursor> iter(cursors);
    Frame_cursor *cursor;
    while ((cursor= iter++))
      cursor->pre_next_row();

    iter.rewind();
    while ((cursor= iter++))
      cursor->next_row();
  }

  ~Cursor_manager() { cursors.delete_elements(); }

private:
  /* List of the cursors that this manager owns. */
  List<Frame_cursor> cursors;
};



//////////////////////////////////////////////////////////////////////////////
// RANGE-type frames
//////////////////////////////////////////////////////////////////////////////

/*
  Frame_range_n_top handles the top end of RANGE-type frame.

  That is, it handles:
    RANGE BETWEEN n PRECEDING AND ...
    RANGE BETWEEN n FOLLOWING AND ...

  Top of the frame doesn't need to check for partition end, since bottom will
  reach it before.
*/

class Frame_range_n_top : public Frame_cursor
{
  Partition_read_cursor cursor;

  Cached_item_item *range_expr;

  Item *n_val;
  Item *item_add;

  const bool is_preceding;

  bool end_of_partition;

  /*
     1  when order_list uses ASC ordering
    -1  when order_list uses DESC ordering
  */
  int order_direction;
public:
  Frame_range_n_top(THD *thd,
                    SQL_I_List<ORDER> *partition_list,
                    SQL_I_List<ORDER> *order_list,
                    bool is_preceding_arg, Item *n_val_arg) :
    cursor(thd, partition_list), n_val(n_val_arg), item_add(NULL),
    is_preceding(is_preceding_arg)
  {
    DBUG_ASSERT(order_list->elements == 1);
    Item *src_expr= order_list->first->item[0];
    if (order_list->first->direction == ORDER::ORDER_ASC)
      order_direction= 1;
    else
      order_direction= -1;

    range_expr= (Cached_item_item*) new_Cached_item(thd, src_expr, FALSE);

    bool use_minus= is_preceding;
    if (order_direction == -1)
      use_minus= !use_minus;

    if (use_minus)
      item_add= new (thd->mem_root) Item_func_minus(thd, src_expr, n_val);
    else
      item_add= new (thd->mem_root) Item_func_plus(thd, src_expr, n_val);

    item_add->fix_fields(thd, &item_add);
  }

  void init(READ_RECORD *info)
  {
    cursor.init(info);
  }

  void pre_next_partition(ha_rows rownum)
  {
    // Save the value of FUNC(current_row)
    range_expr->fetch_value_from(item_add);

    cursor.on_next_partition(rownum);
    end_of_partition= false;
  }

  void next_partition(ha_rows rownum)
  {
    walk_till_non_peer();
  }

  void pre_next_row()
  {
    if (end_of_partition)
      return;
    range_expr->fetch_value_from(item_add);
  }

  void next_row()
  {
    if (end_of_partition)
      return;
    /*
      Ok, our cursor is at the first row R where
        (prev_row + n) >= R
      We need to check about the current row.
    */
    walk_till_non_peer();
  }

  ha_rows get_curr_rownum() const
  {
    return cursor.get_rownum();
  }

  bool is_outside_computation_bounds() const
  {
    if (end_of_partition)
      return true;
    return false;
  }

private:
  void walk_till_non_peer()
  {
    if (cursor.fetch()) // ERROR
      return;
    // Current row is not a peer.
    if (order_direction * range_expr->cmp_read_only() <= 0)
      return;
    remove_value_from_items();

    int res;
    while (!(res= cursor.next()))
    {
      /* Note, no need to fetch the value explicitly here. The partition
         read cursor will fetch it to check if the partition has changed.
         TODO(cvicentiu) make this piece of information not necessary by
         reimplementing Partition_read_cursor.
      */
      if (order_direction * range_expr->cmp_read_only() <= 0)
        break;
      remove_value_from_items();
    }
    if (res)
      end_of_partition= true;
  }

};


/*
  Frame_range_n_bottom handles bottom end of RANGE-type frame.

  That is, it handles frame bounds in form:
    RANGE BETWEEN ... AND n PRECEDING
    RANGE BETWEEN ... AND n FOLLOWING

  Bottom end moves first so it needs to check for partition end
  (todo: unless it's PRECEDING and in that case it doesnt)
  (todo: factor out common parts with Frame_range_n_top into
   a common ancestor)
*/

class Frame_range_n_bottom: public Frame_cursor
{
  Partition_read_cursor cursor;

  Cached_item_item *range_expr;

  Item *n_val;
  Item *item_add;

  const bool is_preceding;

  bool end_of_partition;

  /*
     1  when order_list uses ASC ordering
    -1  when order_list uses DESC ordering
  */
  int order_direction;
public:
  Frame_range_n_bottom(THD *thd,
                       SQL_I_List<ORDER> *partition_list,
                       SQL_I_List<ORDER> *order_list,
                       bool is_preceding_arg, Item *n_val_arg) :
    cursor(thd, partition_list), n_val(n_val_arg), item_add(NULL),
    is_preceding(is_preceding_arg), added_values(false)
  {
    DBUG_ASSERT(order_list->elements == 1);
    Item *src_expr= order_list->first->item[0];

    if (order_list->first->direction == ORDER::ORDER_ASC)
      order_direction= 1;
    else
      order_direction= -1;

    range_expr= (Cached_item_item*) new_Cached_item(thd, src_expr, FALSE);

    bool use_minus= is_preceding;
    if (order_direction == -1)
      use_minus= !use_minus;

    if (use_minus)
      item_add= new (thd->mem_root) Item_func_minus(thd, src_expr, n_val);
    else
      item_add= new (thd->mem_root) Item_func_plus(thd, src_expr, n_val);

    item_add->fix_fields(thd, &item_add);
  }

  void init(READ_RECORD *info)
  {
    cursor.init(info);
  }

  void pre_next_partition(ha_rows rownum)
  {
    // Save the value of FUNC(current_row)
    range_expr->fetch_value_from(item_add);

    cursor.on_next_partition(rownum);
    end_of_partition= false;
    added_values= false;
  }

  void next_partition(ha_rows rownum)
  {
    cursor.move_to(rownum);
    walk_till_non_peer();
  }

  void pre_next_row()
  {
    if (end_of_partition)
      return;
    range_expr->fetch_value_from(item_add);
  }

  void next_row()
  {
    if (end_of_partition)
      return;
    /*
      Ok, our cursor is at the first row R where
        (prev_row + n) >= R
      We need to check about the current row.
    */
    walk_till_non_peer();
  }

  bool is_outside_computation_bounds() const
  {
    if (!added_values)
      return true;
    return false;
  }

  ha_rows get_curr_rownum() const
  {
    if (end_of_partition)
      return cursor.get_rownum(); // Cursor does not pass over partition bound.
    else
      return cursor.get_rownum() - 1; // Cursor is placed on first non peer.
  }

private:
  bool added_values;

  void walk_till_non_peer()
  {
    cursor.fetch();
    // Current row is not a peer.
    if (order_direction * range_expr->cmp_read_only() < 0)
      return;

    add_value_to_items(); // Add current row.
    added_values= true;
    int res;
    while (!(res= cursor.next()))
    {
      if (order_direction * range_expr->cmp_read_only() < 0)
        break;
      add_value_to_items();
    }
    if (res)
      end_of_partition= true;
  }
};


/*
  RANGE BETWEEN ... AND CURRENT ROW, bottom frame bound for CURRENT ROW
     ...
   | peer1
   | peer2  <----- current_row
   | peer3
   +-peer4  <----- the cursor points here. peer4 itself is included.
     nonpeer1
     nonpeer2

  This bound moves in front of the current_row. It should be a the first row
  that is still a peer of the current row.
*/

class Frame_range_current_row_bottom: public Frame_cursor
{
  Partition_read_cursor cursor;

  Group_bound_tracker peer_tracker;

  bool dont_move;
public:
  Frame_range_current_row_bottom(THD *thd,
                                 SQL_I_List<ORDER> *partition_list,
                                 SQL_I_List<ORDER> *order_list) :
    cursor(thd, partition_list), peer_tracker(thd, order_list)
  {
  }

  void init(READ_RECORD *info)
  {
    cursor.init(info);
    peer_tracker.init();
  }

  void pre_next_partition(ha_rows rownum)
  {
    // Save the value of the current_row
    peer_tracker.check_if_next_group();
    cursor.on_next_partition(rownum);
    // Add the current row now because our cursor has already seen it
    add_value_to_items();
  }

  void next_partition(ha_rows rownum)
  {
    walk_till_non_peer();
  }

  void pre_next_row()
  {
    dont_move= !peer_tracker.check_if_next_group();
  }

  void next_row()
  {
    // Check if our cursor is pointing at a peer of the current row.
    // If not, move forward until that becomes true
    if (dont_move)
    {
      /*
        Our current is not a peer of the current row.
        No need to move the bound.
      */
      return;
    }
    walk_till_non_peer();
  }

  ha_rows get_curr_rownum() const
  {
    return cursor.get_rownum();
  }

private:
  void walk_till_non_peer()
  {
    /*
      Walk forward until we've met first row that's not a peer of the current
      row
    */
    while (!cursor.next())
    {
      if (peer_tracker.compare_with_cache())
      {
        cursor.prev(); // Move to our peer.
        break;
      }

      add_value_to_items();
    }
  }
};


/*
  RANGE BETWEEN CURRENT ROW AND .... Top CURRENT ROW, RANGE-type frame bound

      nonpeer1
      nonpeer2
    +-peer1  <----- the cursor points here. peer1 itself is included.
    | peer2  
    | peer3  <----- current_row
    | peer4 
      ... 

  It moves behind the current_row. It is located right after the first peer of
  the current_row.
*/

class Frame_range_current_row_top : public Frame_cursor
{
  Group_bound_tracker bound_tracker;

  Table_read_cursor cursor;
  Group_bound_tracker peer_tracker;

  bool move;
public:
  Frame_range_current_row_top(THD *thd,
                              SQL_I_List<ORDER> *partition_list,
                              SQL_I_List<ORDER> *order_list) :
    bound_tracker(thd, partition_list), cursor(), peer_tracker(thd, order_list),
    move(false)
  {}

  void init(READ_RECORD *info)
  {
    bound_tracker.init();

    cursor.init(info);
    peer_tracker.init();
  }

  void pre_next_partition(ha_rows rownum)
  {
    // Fetch the value from the first row
    peer_tracker.check_if_next_group();
    cursor.move_to(rownum);
  }

  void next_partition(ha_rows rownum) {}

  void pre_next_row()
  {
    // Check if the new current_row is a peer of the row that our cursor is
    // pointing to.
    move= peer_tracker.check_if_next_group();
  }

  void next_row()
  {
    if (move)
    {
      /*
        Our cursor is pointing at the first row that was a peer of the previous
        current row. Or, it was the first row in the partition.
      */
      if (cursor.fetch())
        return;

      // todo: need the following check ?
      if (!peer_tracker.compare_with_cache())
        return;
      remove_value_from_items();

      do
      {
        if (cursor.next() || cursor.fetch())
          return;
        if (!peer_tracker.compare_with_cache())
          return;
        remove_value_from_items();
      }
      while (1);
    }
  }

  ha_rows get_curr_rownum() const
  {
    return cursor.get_rownum();
  }
};


/////////////////////////////////////////////////////////////////////////////
// UNBOUNDED frame bounds (shared between RANGE and ROWS)
/////////////////////////////////////////////////////////////////////////////

/*
  UNBOUNDED PRECEDING frame bound
*/
class Frame_unbounded_preceding : public Frame_cursor
{
public:
  Frame_unbounded_preceding(THD *thd,
                            SQL_I_List<ORDER> *partition_list,
                            SQL_I_List<ORDER> *order_list)
  {}

  void init(READ_RECORD *info) {}

  void next_partition(ha_rows rownum)
  {
    /*
      UNBOUNDED PRECEDING frame end just stays on the first row of the
      partition. We are top of the frame, so we don't need to update the sum
      function.
    */
    curr_rownum= rownum;
  }

  void next_row()
  {
    /* Do nothing, UNBOUNDED PRECEDING frame end doesn't move. */
  }

  ha_rows get_curr_rownum() const
  {
    return curr_rownum;
  }

private:
  ha_rows curr_rownum;
};


/*
  UNBOUNDED FOLLOWING frame bound
*/

class Frame_unbounded_following : public Frame_cursor
{
protected:
  Partition_read_cursor cursor;

public:
  Frame_unbounded_following(THD *thd,
      SQL_I_List<ORDER> *partition_list,
      SQL_I_List<ORDER> *order_list) :
    cursor(thd, partition_list) {}

  void init(READ_RECORD *info)
  {
    cursor.init(info);
  }

  void pre_next_partition(ha_rows rownum)
  {
    cursor.on_next_partition(rownum);
  }

  void next_partition(ha_rows rownum)
  {
    /* Activate the first row */
    cursor.fetch();
    add_value_to_items();

    /* Walk to the end of the partition, updating the SUM function */
    while (!cursor.next())
    {
      add_value_to_items();
    }
  }

  void next_row()
  {
    /* Do nothing, UNBOUNDED FOLLOWING frame end doesn't move */
  }

  ha_rows get_curr_rownum() const
  {
    return cursor.get_rownum();
  }
};


class Frame_unbounded_following_set_count : public Frame_unbounded_following
{
public:
  Frame_unbounded_following_set_count(
      THD *thd,
      SQL_I_List<ORDER> *partition_list, SQL_I_List<ORDER> *order_list) :
    Frame_unbounded_following(thd, partition_list, order_list) {}

  void next_partition(ha_rows rownum)
  {
    ha_rows num_rows_in_partition= 0;
    if (cursor.fetch())
      return;
    num_rows_in_partition++;

    /* Walk to the end of the partition, find how many rows there are. */
    while (!cursor.next())
      num_rows_in_partition++;
    set_win_funcs_row_count(num_rows_in_partition);
  }

  ha_rows get_curr_rownum() const
  {
    return cursor.get_rownum();
  }

protected:
  void set_win_funcs_row_count(ha_rows num_rows_in_partition)
  {
    List_iterator_fast<Item_sum> it(sum_functions);
    Item_sum* item;
    while ((item= it++))
      item->set_partition_row_count(num_rows_in_partition);
  }
};

class Frame_unbounded_following_set_count_no_nulls:
            public Frame_unbounded_following_set_count
{

public:
  Frame_unbounded_following_set_count_no_nulls(THD *thd,
      SQL_I_List<ORDER> *partition_list,
      SQL_I_List<ORDER> *order_list) :
  Frame_unbounded_following_set_count(thd,partition_list, order_list)
  {
    order_item= order_list->first->item[0];
  }
  void next_partition(ha_rows rownum)
  {
    ha_rows num_rows_in_partition= 0;
    if (cursor.fetch())
      return;

    /* Walk to the end of the partition, find how many rows there are. */
    do
    {
      if (!order_item->is_null())
        num_rows_in_partition++;
    } while (!cursor.next());

    set_win_funcs_row_count(num_rows_in_partition);
  }

  ha_rows get_curr_rownum() const
  {
    return cursor.get_rownum();
  }

private:
  Item* order_item;
};

/////////////////////////////////////////////////////////////////////////////
// ROWS-type frame bounds
/////////////////////////////////////////////////////////////////////////////
/*
  ROWS $n PRECEDING frame bound

*/
class Frame_n_rows_preceding : public Frame_cursor
{
  /* Whether this is top of the frame or bottom */
  const bool is_top_bound;
  const ha_rows n_rows;

  /* Number of rows that we need to skip before our cursor starts moving */
  ha_rows n_rows_behind;

  Table_read_cursor cursor;
public:
  Frame_n_rows_preceding(bool is_top_bound_arg, ha_rows n_rows_arg) :
    is_top_bound(is_top_bound_arg), n_rows(n_rows_arg), n_rows_behind(0)
  {}

  void init(READ_RECORD *info)
  {
    cursor.init(info);
  }

  void next_partition(ha_rows rownum)
  {
    /*
      Position our cursor to point at the first row in the new partition
      (for rownum=0, it is already there, otherwise, it lags behind)
    */
    cursor.move_to(rownum);
    /* Cursor is in the same spot as current row. */
    n_rows_behind= 0;

    /*
      Suppose the bound is ROWS 2 PRECEDING, and current row is row#n:
        ...
        n-3
        n-2 --- bound row
        n-1
         n  --- current_row
        ...
       The bound should point at row #(n-2). Bounds are inclusive, so
        - bottom bound should add row #(n-2) into the window function
        - top bound should remove row (#n-3) from the window function.
    */
    move_cursor_if_possible();

  }

  void next_row()
  {
    n_rows_behind++;
    move_cursor_if_possible();
  }

  bool is_outside_computation_bounds() const
  {
    /* As a bottom boundary, rows have not yet been added. */
    if (!is_top_bound && n_rows - n_rows_behind)
      return true;
    return false;
  }

  ha_rows get_curr_rownum() const
  {
    return cursor.get_rownum();
  }

private:
  void move_cursor_if_possible()
  {
    longlong rows_difference= n_rows - n_rows_behind;
    if (rows_difference > 0) /* We still have to wait. */
      return;

      /* The cursor points to the first row in the frame. */
    if (rows_difference == 0)
    {
      if (!is_top_bound)
      {
        cursor.fetch();
        add_value_to_items();
      }
      /* For top bound we don't have to remove anything as nothing was added. */
      return;
    }

    /* We need to catch up by one row. */
    DBUG_ASSERT(rows_difference == -1);

    if (is_top_bound)
    {
      cursor.fetch();
      remove_value_from_items();
      cursor.next();
    }
    else
    {
      cursor.next();
      cursor.fetch();
      add_value_to_items();
    }
    /* We've advanced one row. We are no longer behind. */
    n_rows_behind--;
  }
};


/*
  ROWS ... CURRENT ROW, Bottom bound.

  This case is moved to separate class because here we don't need to maintain
  our own cursor, or check for partition bound.
*/

class Frame_rows_current_row_bottom : public Frame_cursor
{
public:

  Frame_rows_current_row_bottom() : curr_rownum(0) {}

  void pre_next_partition(ha_rows rownum)
  {
    add_value_to_items();
    curr_rownum= rownum;
  }

  void next_partition(ha_rows rownum) {}

  void pre_next_row()
  {
    /* Temp table's current row is current_row. Add it to the window func */
    add_value_to_items();
  }

  void next_row()
  {
    curr_rownum++;
  };

  ha_rows get_curr_rownum() const
  {
    return curr_rownum;
  }

private:
  ha_rows curr_rownum;
};


/*
  ROWS-type CURRENT ROW, top bound.

  This serves for processing "ROWS BETWEEN CURRENT ROW AND ..." frames.

      n-1
       n  --+  --- current_row, and top frame bound
      n+1   |
      ...   |

  when the current_row moves to row #n, this frame bound should remove the
  row #(n-1) from the window function.

  In other words, we need what "ROWS PRECEDING 0" provides.
*/
class Frame_rows_current_row_top: public Frame_n_rows_preceding

{
public:
  Frame_rows_current_row_top() :
    Frame_n_rows_preceding(true /*top*/, 0 /* n_rows */)
  {}
};


/*
  ROWS $n FOLLOWING frame bound.
*/

class Frame_n_rows_following : public Frame_cursor
{
  /* Whether this is top of the frame or bottom */
  const bool is_top_bound;
  const ha_rows n_rows;

  Partition_read_cursor cursor;
  bool at_partition_end;
public:
  Frame_n_rows_following(THD *thd,
            SQL_I_List<ORDER> *partition_list,
            SQL_I_List<ORDER> *order_list,
            bool is_top_bound_arg, ha_rows n_rows_arg) :
    is_top_bound(is_top_bound_arg), n_rows(n_rows_arg),
    cursor(thd, partition_list)
  {
  }

  void init(READ_RECORD *info)
  {
    cursor.init(info);
    at_partition_end= false;
  }

  void pre_next_partition(ha_rows rownum)
  {
    at_partition_end= false;

    cursor.on_next_partition(rownum);
  }

  /* Move our cursor to be n_rows ahead.  */
  void next_partition(ha_rows rownum)
  {
    if (is_top_bound)
      next_part_top(rownum);
    else
      next_part_bottom(rownum);
  }

  void next_row()
  {
    if (is_top_bound)
      next_row_top();
    else
      next_row_bottom();
  }

  bool is_outside_computation_bounds() const
  {
    /*
       The top bound can go over the current partition. In this case,
       the sum function has 0 values added to it.
    */
    if (at_partition_end && is_top_bound)
      return true;
    return false;
  }

  ha_rows get_curr_rownum() const
  {
    return cursor.get_rownum();
  }

private:
  void next_part_top(ha_rows rownum)
  {
    for (ha_rows i= 0; i < n_rows; i++)
    {
      if (cursor.fetch())
        break;
      remove_value_from_items();
      if (cursor.next())
        at_partition_end= true;
    }
  }

  void next_part_bottom(ha_rows rownum)
  {
    if (cursor.fetch())
      return;
    add_value_to_items();

    for (ha_rows i= 0; i < n_rows; i++)
    {
      if (cursor.next())
      {
        at_partition_end= true;
        break;
      }
      add_value_to_items();
    }
    return;
  }

  void next_row_top()
  {
    if (cursor.fetch()) // PART END OR FAILURE
    {
      at_partition_end= true;
      return;
    }
    remove_value_from_items();
    if (cursor.next())
    {
      at_partition_end= true;
      return;
    }
  }

  void next_row_bottom()
  {
    if (at_partition_end)
      return;

    if (cursor.next())
    {
      at_partition_end= true;
      return;
    }

    add_value_to_items();

  }
};

/*
  A cursor that performs a table scan between two indices. The indices
  are provided by the two cursors representing the top and bottom bound
  of the window function's frame definition.

  Each scan clears the sum function.

  NOTE:
    The cursor does not alter the top and bottom cursors.
    This type of cursor is expensive computational wise. This is only to be
    used when the sum functions do not support removal.
*/
class Frame_scan_cursor : public Frame_cursor
{
public:
  Frame_scan_cursor(const Frame_cursor &top_bound,
                    const Frame_cursor &bottom_bound) :
    top_bound(top_bound), bottom_bound(bottom_bound) {}

  void init(READ_RECORD *info)
  {
    cursor.init(info);
  }

  void pre_next_partition(ha_rows rownum)
  {
    /* TODO(cvicentiu) Sum functions get cleared on next partition anyway during
       the window function computation algorithm. Either perform this only in
       cursors, or remove it from pre_next_partition.
    */
    curr_rownum= rownum;
    clear_sum_functions();
  }

  void next_partition(ha_rows rownum)
  {
    compute_values_for_current_row();
  }

  void pre_next_row()
  {
    clear_sum_functions();
  }

  void next_row()
  {
    curr_rownum++;
    compute_values_for_current_row();
  }

  ha_rows get_curr_rownum() const
  {
    return curr_rownum;
  }

private:
  const Frame_cursor &top_bound;
  const Frame_cursor &bottom_bound;
  Table_read_cursor cursor;
  ha_rows curr_rownum;

  /* Scan the rows between the top bound and bottom bound. Add all the values
     between them, top bound row  and bottom bound row inclusive. */
  void compute_values_for_current_row()
  {
    if (top_bound.is_outside_computation_bounds() ||
        bottom_bound.is_outside_computation_bounds())
      return;

    ha_rows start_rownum= top_bound.get_curr_rownum();
    ha_rows bottom_rownum= bottom_bound.get_curr_rownum();
    DBUG_PRINT("info", ("COMPUTING (%llu %llu)", start_rownum, bottom_rownum));

    cursor.move_to(start_rownum);

    for (ha_rows idx= start_rownum; idx <= bottom_rownum; idx++)
    {
      if (cursor.fetch()) //EOF
        break;
      add_value_to_items();
      if (cursor.next()) // EOF
        break;
    }
  }
};

/* A cursor that follows a target cursor. Each time a new row is added,
   the window functions are cleared and only have the row at which the target
   is point at added to them.

   The window functions are cleared if the bounds or the position cursors are
   outside computational bounds.
*/
class Frame_positional_cursor : public Frame_cursor
{
 public:
  Frame_positional_cursor(const Frame_cursor &position_cursor) :
    position_cursor(position_cursor), top_bound(NULL),
    bottom_bound(NULL), offset(NULL), overflowed(false),
    negative_offset(false) {}

  Frame_positional_cursor(const Frame_cursor &position_cursor,
                          const Frame_cursor &top_bound,
                          const Frame_cursor &bottom_bound,
                          Item &offset,
                          bool negative_offset) :
    position_cursor(position_cursor), top_bound(&top_bound),
    bottom_bound(&bottom_bound), offset(&offset),
    negative_offset(negative_offset) {}

  void init(READ_RECORD *info)
  {
    cursor.init(info);
  }

  void pre_next_partition(ha_rows rownum)
  {
    /* The offset is dependant on the current row values. We can only get
     * it here accurately. When fetching other rows, it changes. */
    save_offset_value();
  }

  void next_partition(ha_rows rownum)
  {
    save_positional_value();
  }

  void pre_next_row()
  {
    /* The offset is dependant on the current row values. We can only get
     * it here accurately. When fetching other rows, it changes. */
    save_offset_value();
  }

  void next_row()
  {
    save_positional_value();
  }

  ha_rows get_curr_rownum() const
  {
    return position_cursor.get_curr_rownum();
  }

private:
  /* Check if a our position is within bounds.
   * The position is passed as a parameter to avoid recalculating it. */
  bool position_is_within_bounds()
  {
    if (!offset)
      return !position_cursor.is_outside_computation_bounds();

    if (overflowed)
      return false;

    /* No valid bound to compare to. */
    if (position_cursor.is_outside_computation_bounds() ||
        top_bound->is_outside_computation_bounds() ||
        bottom_bound->is_outside_computation_bounds())
      return false;

    /* We are over the bound. */
    if (position < top_bound->get_curr_rownum())
      return false;
    if (position > bottom_bound->get_curr_rownum())
      return false;

    return true;
  }

  /* Get the current position, accounting for the offset value, if present.
     NOTE: This function does not check over/underflow.
  */
  void get_current_position()
  {
    position = position_cursor.get_curr_rownum();
    overflowed= false;
    if (offset)
    {
      if (offset_value < 0 &&
          position + offset_value > position)
      {
        overflowed= true;
      }
      if (offset_value > 0 &&
          position + offset_value < position)
      {
        overflowed= true;
      }
      position += offset_value;
    }
  }

  void save_offset_value()
  {
    if (offset)
      offset_value= offset->val_int() * (negative_offset ? -1 : 1);
    else
      offset_value= 0;
  }

  void save_positional_value()
  {
    get_current_position();
    if (!position_is_within_bounds())
      clear_sum_functions();
    else
    {
      cursor.move_to(position);
      cursor.fetch();
      add_value_to_items();
    }
  }

  const Frame_cursor &position_cursor;
  const Frame_cursor *top_bound;
  const Frame_cursor *bottom_bound;
  Item *offset;
  Table_read_cursor cursor;
  ha_rows position;
  longlong offset_value;
  bool overflowed;

  bool negative_offset;
};


/*
  Get a Frame_cursor for a frame bound. This is a "factory function".
*/
Frame_cursor *get_frame_cursor(THD *thd, Window_spec *spec, bool is_top_bound)
{
  Window_frame *frame= spec->window_frame;
  if (!frame)
  {
    /*
      The docs say this about the lack of frame clause:

        Let WD be a window structure descriptor.
        ...
        If WD has no window framing clause, then
        Case:
        i) If the window ordering clause of WD is not present, then WF is the
           window partition of R.
        ii) Otherwise, WF consists of all rows of the partition of R that
           precede R or are peers of R in the window ordering of the window
           partition defined by the window ordering clause.

        For case #ii, the frame bounds essentially are "RANGE BETWEEN UNBOUNDED
        PRECEDING AND CURRENT ROW".
        For the case #i, without ordering clause all rows are considered peers,
        so again the same frame bounds can be used.
    */
    if (is_top_bound)
      return new Frame_unbounded_preceding(thd,
                                           spec->partition_list,
                                           spec->order_list);
    else
      return new Frame_range_current_row_bottom(thd,
                                                spec->partition_list,
                                                spec->order_list);
  }

  Window_frame_bound *bound= is_top_bound? frame->top_bound :
                                           frame->bottom_bound;

  if (bound->precedence_type == Window_frame_bound::PRECEDING ||
      bound->precedence_type == Window_frame_bound::FOLLOWING)
  {
    bool is_preceding= (bound->precedence_type ==
                        Window_frame_bound::PRECEDING);

    if (bound->offset == NULL) /* this is UNBOUNDED */
    {
      /* The following serve both RANGE and ROWS: */
      if (is_preceding)
        return new Frame_unbounded_preceding(thd,
                                             spec->partition_list,
                                             spec->order_list);

      return new Frame_unbounded_following(thd,
                                           spec->partition_list,
                                           spec->order_list);
    }

    if (frame->units == Window_frame::UNITS_ROWS)
    {
      ha_rows n_rows= bound->offset->val_int();
      /* These should be handled in the parser */
      DBUG_ASSERT(!bound->offset->null_value);
      DBUG_ASSERT((longlong) n_rows >= 0);
      if (is_preceding)
        return new Frame_n_rows_preceding(is_top_bound, n_rows);

      return new Frame_n_rows_following(
          thd, spec->partition_list, spec->order_list,
          is_top_bound, n_rows);
    }
    else
    {
      if (is_top_bound)
        return new Frame_range_n_top(
            thd, spec->partition_list, spec->order_list,
            is_preceding, bound->offset);

      return new Frame_range_n_bottom(thd,
          spec->partition_list, spec->order_list,
          is_preceding, bound->offset);
    }
  }

  if (bound->precedence_type == Window_frame_bound::CURRENT)
  {
    if (frame->units == Window_frame::UNITS_ROWS)
    {
      if (is_top_bound)
        return new Frame_rows_current_row_top;

      return new Frame_rows_current_row_bottom;
    }
    else
    {
      if (is_top_bound)
        return new Frame_range_current_row_top(
            thd, spec->partition_list, spec->order_list);

      return new Frame_range_current_row_bottom(
          thd, spec->partition_list, spec->order_list);
    }
  }
  return NULL;
}

static
void add_special_frame_cursors(THD *thd, Cursor_manager *cursor_manager,
                               Item_window_func *window_func)
{
  Window_spec *spec= window_func->window_spec;
  Item_sum *item_sum= window_func->window_func();
  DBUG_PRINT("info", ("Get arg count: %d", item_sum->get_arg_count()));
  Frame_cursor *fc;
  switch (item_sum->sum_func())
  {
    case Item_sum::CUME_DIST_FUNC:
      fc= new Frame_unbounded_preceding(thd,
                                        spec->partition_list,
                                        spec->order_list);
      fc->add_sum_func(item_sum);
      cursor_manager->add_cursor(fc);
      fc= new Frame_range_current_row_bottom(thd,
                                             spec->partition_list,
                                             spec->order_list);
      fc->add_sum_func(item_sum);
      cursor_manager->add_cursor(fc);
      break;
    case Item_sum::LEAD_FUNC:
    case Item_sum::LAG_FUNC:
    {
      Frame_cursor *bottom_bound= new Frame_unbounded_following(thd,
                                                                spec->partition_list,
                                                                spec->order_list);
      Frame_cursor *top_bound= new Frame_unbounded_preceding(thd,
                                                             spec->partition_list,
                                                             spec->order_list);
      Frame_cursor *current_row_pos= new Frame_rows_current_row_bottom;
      cursor_manager->add_cursor(bottom_bound);
      cursor_manager->add_cursor(top_bound);
      cursor_manager->add_cursor(current_row_pos);
      DBUG_ASSERT(item_sum->fixed());
      bool negative_offset= item_sum->sum_func() == Item_sum::LAG_FUNC;
      fc= new Frame_positional_cursor(*current_row_pos,
                                      *top_bound, *bottom_bound,
                                      *item_sum->get_arg(1),
                                      negative_offset);
      fc->add_sum_func(item_sum);
      cursor_manager->add_cursor(fc);
      break;
    }
    case Item_sum::FIRST_VALUE_FUNC:
    {
      Frame_cursor *bottom_bound= get_frame_cursor(thd, spec, false);
      Frame_cursor *top_bound= get_frame_cursor(thd, spec, true);
      cursor_manager->add_cursor(bottom_bound);
      cursor_manager->add_cursor(top_bound);
      DBUG_ASSERT(item_sum->fixed());
      Item *offset_item= new (thd->mem_root) Item_int(thd, 0);
      offset_item->fix_fields(thd, &offset_item);
      fc= new Frame_positional_cursor(*top_bound,
                                      *top_bound, *bottom_bound,
                                      *offset_item, false);
      fc->add_sum_func(item_sum);
      cursor_manager->add_cursor(fc);
      break;
    }
    case Item_sum::LAST_VALUE_FUNC:
    {
      Frame_cursor *bottom_bound= get_frame_cursor(thd, spec, false);
      Frame_cursor *top_bound= get_frame_cursor(thd, spec, true);
      cursor_manager->add_cursor(bottom_bound);
      cursor_manager->add_cursor(top_bound);
      DBUG_ASSERT(item_sum->fixed());
      Item *offset_item= new (thd->mem_root) Item_int(thd, 0);
      offset_item->fix_fields(thd, &offset_item);
      fc= new Frame_positional_cursor(*bottom_bound,
                                      *top_bound, *bottom_bound,
                                      *offset_item, false);
      fc->add_sum_func(item_sum);
      cursor_manager->add_cursor(fc);
      break;
    }
    case Item_sum::NTH_VALUE_FUNC:
    {
      Frame_cursor *bottom_bound= get_frame_cursor(thd, spec, false);
      Frame_cursor *top_bound= get_frame_cursor(thd, spec, true);
      cursor_manager->add_cursor(bottom_bound);
      cursor_manager->add_cursor(top_bound);
      DBUG_ASSERT(item_sum->fixed());
      Item *int_item= new (thd->mem_root) Item_int(thd, 1);
      Item *offset_func= new (thd->mem_root)
                              Item_func_minus(thd, item_sum->get_arg(1),
                                              int_item);
      offset_func->fix_fields(thd, &offset_func);
      fc= new Frame_positional_cursor(*top_bound,
                                      *top_bound, *bottom_bound,
                                      *offset_func, false);
      fc->add_sum_func(item_sum);
      cursor_manager->add_cursor(fc);
      break;
    }
    case Item_sum::PERCENTILE_CONT_FUNC:
    case Item_sum::PERCENTILE_DISC_FUNC:
    {
      fc= new Frame_unbounded_preceding(thd,
                                        spec->partition_list,
                                        spec->order_list);
      fc->add_sum_func(item_sum);
      cursor_manager->add_cursor(fc);
      fc= new Frame_unbounded_following(thd,
                                          spec->partition_list,
                                          spec->order_list);
      fc->add_sum_func(item_sum);
      cursor_manager->add_cursor(fc);
      break;
    }
    default:
      fc= new Frame_unbounded_preceding(
              thd, spec->partition_list, spec->order_list);
      fc->add_sum_func(item_sum);
      cursor_manager->add_cursor(fc);

      fc= new Frame_rows_current_row_bottom;
      fc->add_sum_func(item_sum);
      cursor_manager->add_cursor(fc);
  }
}


static bool is_computed_with_remove(Item_sum::Sumfunctype sum_func)
{
  switch (sum_func)
  {
    case Item_sum::CUME_DIST_FUNC:
    case Item_sum::ROW_NUMBER_FUNC:
    case Item_sum::RANK_FUNC:
    case Item_sum::DENSE_RANK_FUNC:
    case Item_sum::NTILE_FUNC:
    case Item_sum::FIRST_VALUE_FUNC:
    case Item_sum::LAST_VALUE_FUNC:
    case Item_sum::PERCENTILE_CONT_FUNC:
    case Item_sum::PERCENTILE_DISC_FUNC:
      return false;
    default:
      return true;
  }
}
/*
   Create required frame cursors for the list of window functions.
   Register all functions to their appropriate cursors.
   If the window functions share the same frame specification,
   those window functions will be registered to the same cursor.
*/
void get_window_functions_required_cursors(
    THD *thd,
    List<Item_window_func>& window_functions,
    List<Cursor_manager> *cursor_managers)
{
  List_iterator_fast<Item_window_func> it(window_functions);
  Item_window_func* item_win_func;
  Item_sum *sum_func;
  while ((item_win_func= it++))
  {
    Cursor_manager *cursor_manager = new Cursor_manager();
    sum_func = item_win_func->window_func();
    Frame_cursor *fc;
    /*
      Some window functions require the partition size for computing values.
      Add a cursor that retrieves it as the first one in the list if necessary.
    */
    if (item_win_func->requires_partition_size())
    {
      if (item_win_func->only_single_element_order_list())
      {
        fc= new Frame_unbounded_following_set_count_no_nulls(thd,
                item_win_func->window_spec->partition_list,
                item_win_func->window_spec->order_list);
      }
      else
      {
        fc= new Frame_unbounded_following_set_count(thd,
                item_win_func->window_spec->partition_list,
                item_win_func->window_spec->order_list);
      }
      fc->add_sum_func(sum_func);
      cursor_manager->add_cursor(fc);
    }

    /*
      If it is not a regular window function that follows frame specifications,
      and/or specific cursors are required. ROW_NUM, RANK, NTILE and others
      follow such rules. Check is_frame_prohibited check for the full list.

      TODO(cvicentiu) This approach is messy. Every time a function allows
      computation in a certain way, we have to add an extra method to this
      factory function. It is better to have window functions output
      their own cursors, as needed. This way, the logic is bound
      only to the implementation of said window function. Regular aggregate
      functions can keep the default frame generating code, overwrite it or
      add to it.
    */
    if (item_win_func->is_frame_prohibited() ||
        item_win_func->requires_special_cursors())
    {
      add_special_frame_cursors(thd, cursor_manager, item_win_func);
      cursor_managers->push_back(cursor_manager);
      continue;
    }

    Frame_cursor *frame_bottom= get_frame_cursor(thd,
        item_win_func->window_spec, false);
    Frame_cursor *frame_top= get_frame_cursor(thd,
        item_win_func->window_spec, true);

    frame_bottom->add_sum_func(sum_func);
    frame_top->add_sum_func(sum_func);

    /*
       The order of these cursors is important. A sum function
       must first add values (via frame_bottom) then remove them via
       frame_top. Removing items first doesn't make sense in the case of all
       window functions.
    */
    cursor_manager->add_cursor(frame_bottom);
    cursor_manager->add_cursor(frame_top);
    if (is_computed_with_remove(sum_func->sum_func()) &&
        !sum_func->supports_removal())
    {
      frame_bottom->set_no_action();
      frame_top->set_no_action();
      Frame_cursor *scan_cursor= new Frame_scan_cursor(*frame_top,
                                                       *frame_bottom);
      scan_cursor->add_sum_func(sum_func);
      cursor_manager->add_cursor(scan_cursor);

    }
    cursor_managers->push_back(cursor_manager);
  }
}

/**
  Helper function that takes a list of window functions and writes
  their values in the current table record.
*/
static
bool save_window_function_values(List<Item_window_func>& window_functions,
                                 TABLE *tbl, uchar *rowid_buf)
{
  List_iterator_fast<Item_window_func> iter(window_functions);
  JOIN_TAB *join_tab= tbl->reginfo.join_tab;
  tbl->file->ha_rnd_pos(tbl->record[0], rowid_buf);
  store_record(tbl, record[1]);
  while (Item_window_func *item_win= iter++)
    item_win->save_in_field(item_win->result_field, true);

  /*
    In case we have window functions present, an extra step is required
    to compute all the fields from the temporary table.
    In case we have a compound expression such as: expr + expr,
    where one of the terms has a window function inside it, only
    after computing window function values we actually know the true
    final result of the compounded expression.

    Go through all the func items and save their values once again in the
    corresponding temp table fields. Do this for each row in the table.

    This needs to be done earlier because ORDER BY clause can also have
    a window function, so we need to make sure all the fields of the temp.table
    are updated before we do the filesort. So is best to update the other fields
    that contain the window functions along with the computation of window
    functions.
  */

  Item **func_ptr= join_tab->tmp_table_param->items_to_copy;
  Item *func;
  for (; (func = *func_ptr) ; func_ptr++)
  {
    if (func->with_window_func() && func->type() != Item::WINDOW_FUNC_ITEM)
      func->save_in_result_field(true);
  }

  int err= tbl->file->ha_update_row(tbl->record[1], tbl->record[0]);
  if (err && err != HA_ERR_RECORD_IS_THE_SAME)
    return true;

  return false;
}

/*
  TODO(cvicentiu) update this comment to reflect the new execution.

  Streamed window function computation with window frames.

  We make a single pass over the ordered temp.table, but we're using three
  cursors:
   - current row - the row that we're computing window func value for)
   - start_bound - the start of the frame
   - bottom_bound   - the end of the frame

  All three cursors move together.

  @todo
    Provided bounds have their 'cursors'... is it better to re-clone their
    cursors or re-position them onto the current row?

  @detail
    ROWS BETWEEN 3 PRECEDING  -- frame start
              AND 3 FOLLOWING  -- frame end

                                    /------ frame end (aka BOTTOM)
    Dataset start                   |
     --------====*=======[*]========*========-------->> dataset end
                 |        \  
                 |         +-------- current row
                 |
                 \-------- frame start ("TOP")

    - frame_end moves forward and adds rows into the aggregate function.
    - frame_start follows behind and removes rows from the aggregate function.
    - current_row is the row where the value of aggregate function is stored.

  @TODO:  Only the first cursor needs to check for run-out-of-partition
  condition (Others can catch up by counting rows?)

*/
bool compute_window_func(THD *thd,
                         List<Item_window_func>& window_functions,
                         List<Cursor_manager>& cursor_managers,
                         TABLE *tbl,
                         SORT_INFO *filesort_result)
{
  List_iterator_fast<Item_window_func> iter_win_funcs(window_functions);
  List_iterator_fast<Cursor_manager> iter_cursor_managers(cursor_managers);
  uint err;

  READ_RECORD info;

  if (init_read_record(&info, current_thd, tbl, NULL/*select*/, filesort_result,
                       0, 1, FALSE))
    return true;

  Cursor_manager *cursor_manager;
  while ((cursor_manager= iter_cursor_managers++))
    cursor_manager->initialize_cursors(&info);

  /* One partition tracker for each window function. */
  List<Group_bound_tracker> partition_trackers;
  Item_window_func *win_func;
  while ((win_func= iter_win_funcs++))
  {
    Group_bound_tracker *tracker= new Group_bound_tracker(thd,
                                        win_func->window_spec->partition_list);
    // TODO(cvicentiu) This should be removed and placed in constructor.
    tracker->init();
    partition_trackers.push_back(tracker);
  }

  List_iterator_fast<Group_bound_tracker> iter_part_trackers(partition_trackers);
  ha_rows rownum= 0;
  uchar *rowid_buf= (uchar*) my_malloc(PSI_INSTRUMENT_ME, tbl->file->ref_length, MYF(0));

  while (true)
  {
    if ((err= info.read_record()))
      break; // End of file.

    /* Remember current row so that we can restore it before computing
       each window function. */
    tbl->file->position(tbl->record[0]);
    memcpy(rowid_buf, tbl->file->ref, tbl->file->ref_length);

    iter_win_funcs.rewind();
    iter_part_trackers.rewind();
    iter_cursor_managers.rewind();

    Group_bound_tracker *tracker;
    while ((win_func= iter_win_funcs++) &&
           (tracker= iter_part_trackers++) &&
           (cursor_manager= iter_cursor_managers++))
    {
      if (tracker->check_if_next_group() || (rownum == 0))
      {
        /* TODO(cvicentiu)
           Clearing window functions should happen through cursors. */
        win_func->window_func()->clear();
        cursor_manager->notify_cursors_partition_changed(rownum);
      }
      else
      {
        cursor_manager->notify_cursors_next_row();
      }

      /* Check if we found any error in the window function while adding values
         through cursors. */
      if (unlikely(thd->is_error() || thd->is_killed()))
        break;


      /* Return to current row after notifying cursors for each window
         function. */
      tbl->file->ha_rnd_pos(tbl->record[0], rowid_buf);
    }

    /* We now have computed values for each window function. They can now
       be saved in the current row. */
    save_window_function_values(window_functions, tbl, rowid_buf);

    rownum++;
  }

  my_free(rowid_buf);
  partition_trackers.delete_elements();
  end_read_record(&info);

  return false;
}

/* Make a list that is a concation of two lists of ORDER elements */

static ORDER* concat_order_lists(MEM_ROOT *mem_root, ORDER *list1, ORDER *list2)
{
  if (!list1)
  {
    list1= list2;
    list2= NULL;
  }

  ORDER *res= NULL; // first element in the new list
  ORDER *prev= NULL; // last element in the new list 
  ORDER *cur_list= list1; // this goes through list1, list2
  while (cur_list)
  {
    for (ORDER *cur= cur_list; cur; cur= cur->next)
    {
      ORDER *copy= (ORDER*)alloc_root(mem_root, sizeof(ORDER));
      memcpy(copy, cur, sizeof(ORDER));
      if (prev)
        prev->next= copy;
      prev= copy;
      if (!res)
        res= copy;
    }

    cur_list= (cur_list == list1)? list2: NULL;
  }

  if (prev)
    prev->next= NULL;

  return res;
}

bool Window_func_runner::add_function_to_run(Item_window_func *win_func)
{

  Item_sum *sum_func= win_func->window_func();
  sum_func->setup_window_func(current_thd, win_func->window_spec);

  Item_sum::Sumfunctype type= win_func->window_func()->sum_func();

  switch (type)
  {
    /* Distinct is not yet supported. */
    case Item_sum::GROUP_CONCAT_FUNC:
      my_error(ER_NOT_SUPPORTED_YET, MYF(0),
               "GROUP_CONCAT() aggregate as window function");
      return true;
    case Item_sum::SUM_DISTINCT_FUNC:
      my_error(ER_NOT_SUPPORTED_YET, MYF(0),
               "SUM(DISTINCT) aggregate as window function");
      return true;
    case Item_sum::AVG_DISTINCT_FUNC:
      my_error(ER_NOT_SUPPORTED_YET, MYF(0),
               "AVG(DISTINCT) aggregate as window function");
      return true;
    case Item_sum::COUNT_DISTINCT_FUNC:
      my_error(ER_NOT_SUPPORTED_YET, MYF(0),
               "COUNT(DISTINCT) aggregate as window function");
      return true;
    case Item_sum::JSON_ARRAYAGG_FUNC:
      my_error(ER_NOT_SUPPORTED_YET, MYF(0),
               "JSON_ARRAYAGG() aggregate as window function");
      return true;
    case Item_sum::JSON_OBJECTAGG_FUNC:
      my_error(ER_NOT_SUPPORTED_YET, MYF(0),
               "JSON_OBJECTAGG() aggregate as window function");
      return true;
    default:
      break;
  }

  return window_functions.push_back(win_func);
}


/*
  Compute the value of window function for all rows.
*/
bool Window_func_runner::exec(THD *thd, TABLE *tbl, SORT_INFO *filesort_result)
{
  List_iterator_fast<Item_window_func> it(window_functions);
  Item_window_func *win_func;
  while ((win_func= it++))
  {
    win_func->set_phase_to_computation();
    // TODO(cvicentiu) Setting the aggregator should probably be done during
    // setup of Window_funcs_sort.
    win_func->window_func()->set_aggregator(thd,
                                            Aggregator::SIMPLE_AGGREGATOR);
  }
  it.rewind();

  List<Cursor_manager> cursor_managers;
  get_window_functions_required_cursors(thd, window_functions,
                                        &cursor_managers);

  /* Go through the sorted array and compute the window function */
  bool is_error= compute_window_func(thd,
                                     window_functions,
                                     cursor_managers,
                                     tbl, filesort_result);
  while ((win_func= it++))
  {
    win_func->set_phase_to_retrieval();
  }

  cursor_managers.delete_elements();

  return is_error;
}


bool Window_funcs_sort::exec(JOIN *join, bool keep_filesort_result)
{
  THD *thd= join->thd;
  JOIN_TAB *join_tab= join->join_tab + join->total_join_tab_cnt();

  /* Sort the table based on the most specific sorting criteria of
     the window functions. */
  if (create_sort_index(thd, join, join_tab, filesort))
    return true;

  TABLE *tbl= join_tab->table;
  SORT_INFO *filesort_result= join_tab->filesort_result;

  bool is_error= runner.exec(thd, tbl, filesort_result);

  if (!keep_filesort_result)
  {
    delete join_tab->filesort_result;
    join_tab->filesort_result= NULL;
  }
  return is_error;
}


bool Window_funcs_sort::setup(THD *thd, SQL_SELECT *sel,
                              List_iterator<Item_window_func> &it,
                              JOIN_TAB *join_tab)
{
  Window_spec *spec;
  Item_window_func *win_func= it.peek();  
  Item_window_func *win_func_with_longest_order= NULL;
  int longest_order_elements= -1;

  /* The iterator should point to a valid function at the start of execution. */
  DBUG_ASSERT(win_func);
  do
  {
    spec= win_func->window_spec;
    int win_func_order_elements= spec->partition_list->elements +
                                  spec->order_list->elements;
    if (win_func_order_elements >= longest_order_elements)
    {
      win_func_with_longest_order= win_func;
      longest_order_elements= win_func_order_elements;
    }
    if (runner.add_function_to_run(win_func))
      return true;
    it++;
    win_func= it.peek();
  } while (win_func && !(win_func->marker & MARKER_SORTORDER_CHANGE));

  /*
    The sort criteria must be taken from the last win_func in the group of
    adjacent win_funcs that do not have MARKER_SORTORDER_CHANGE. This is
    because the sort order must be the most specific sorting criteria defined
    within the window function group. This ensures that we sort the table
    in a way that the result is valid for all window functions belonging to
    this Window_funcs_sort.
  */
  spec= win_func_with_longest_order->window_spec;

  ORDER* sort_order= concat_order_lists(thd->mem_root, 
                                        spec->partition_list->first,
                                        spec->order_list->first);
  if (sort_order == NULL) // No partition or order by clause.
  {
    /* TODO(cvicentiu) This is used as a way to allow an empty OVER ()
       clause for window functions. However, a better approach is
       to not call Filesort at all in this case and just read whatever order
       the temporary table has.
       Due to cursors not working for out_of_memory cases (yet!), we have to run
       filesort to generate a sort buffer of the results.
       In this case we sort by the first field of the temporary table.
       We should have this field available, even if it is a window_function
       field. We don't care of the particular sorting result in this case.
     */
    ORDER *order= (ORDER *)alloc_root(thd->mem_root, sizeof(ORDER));
    memset(order, 0, sizeof(*order));
    Item_field *item=
        new (thd->mem_root) Item_field(thd, join_tab->table->field[0]);
    if (item)
      item->set_refers_to_temp_table();
    order->item= (Item **)alloc_root(thd->mem_root, 2 * sizeof(Item *));
    order->item[1]= NULL;
    order->item[0]= item;
    order->field= join_tab->table->field[0];
    sort_order= order;
  }
  filesort= new (thd->mem_root) Filesort(sort_order, HA_POS_ERROR, true, NULL);

  /* Apply the same condition that the subsequent sort has. */
  filesort->select= sel;

  return false;
}


bool Window_funcs_computation::setup(THD *thd,
                                     List<Item_window_func> *window_funcs,
                                     JOIN_TAB *tab)
{
  order_window_funcs_by_window_specs(window_funcs);

  SQL_SELECT *sel= NULL;
  /*
     If the tmp table is filtered during sorting
     (ex: SELECT with HAVING && ORDER BY), we must make sure to keep the
     filtering conditions when we perform sorting for window function
     computation.
  */
  if (tab->filesort && tab->filesort->select)
  {
    sel= tab->filesort->select;
    DBUG_ASSERT(!sel->quick);
  }

  Window_funcs_sort *srt;
  List_iterator<Item_window_func> iter(*window_funcs);
  while (iter.peek())
  {
    if (!(srt= new Window_funcs_sort()) ||
        srt->setup(thd, sel, iter, tab))
    {
      return true;
    }
    win_func_sorts.push_back(srt, thd->mem_root);
  }
  return false;
}


bool Window_funcs_computation::exec(JOIN *join, bool keep_last_filesort_result)
{
  List_iterator<Window_funcs_sort> it(win_func_sorts);
  Window_funcs_sort *srt;
  uint counter= 0; /* Count how many sorts we've executed. */
  /* Execute each sort */
  while ((srt = it++))
  {
    counter++;
    bool keep_filesort_result= keep_last_filesort_result &&
                               counter == win_func_sorts.elements;
    if (srt->exec(join, keep_filesort_result))
      return true;
  }
  return false;
}


void Window_funcs_computation::cleanup()
{
  List_iterator<Window_funcs_sort> it(win_func_sorts);
  Window_funcs_sort *srt;
  while ((srt = it++))
  {
    srt->cleanup();
    delete srt;
  }
}


Explain_aggr_window_funcs*
Window_funcs_computation::save_explain_plan(MEM_ROOT *mem_root, 
                                                 bool is_analyze)
{
  Explain_aggr_window_funcs *xpl= new Explain_aggr_window_funcs;
  List_iterator<Window_funcs_sort> it(win_func_sorts);
  Window_funcs_sort *srt;
  if (!xpl)
    return 0;
  while ((srt = it++))
  {
    Explain_aggr_filesort *eaf=
      new Explain_aggr_filesort(mem_root, is_analyze, srt->filesort);
    if (!eaf)
      return 0;
    xpl->sorts.push_back(eaf, mem_root);
  }
  return xpl;
}


bool st_select_lex::add_window_func(Item_window_func *win_func)
{
  if (parsing_place != SELECT_LIST)
    fields_in_window_functions+= win_func->window_func()->argument_count();
  return window_funcs.push_back(win_func);
}

/////////////////////////////////////////////////////////////////////////////
// Unneeded comments (will be removed when we develop a replacement for
//  the feature that was attempted here
/////////////////////////////////////////////////////////////////////////////
  /*
   TODO Get this code to set can_compute_window_function during preparation,
   not during execution.

   The reason for this is the following:
   Our single scan optimization for window functions without tmp table,
   is valid, if and only if, we only need to perform one sorting operation,
   via filesort. The cases where we need to perform one sorting operation only:

   * A select with only one window function.
   * A select with multiple window functions, but they must have their
     partition and order by clauses compatible. This means that one ordering
     is acceptable for both window functions.

       For example:
       partition by a, b, c; order by d, e    results in sorting by a b c d e.
       partition by a; order by d             results in sorting by a d.

       This kind of sorting is compatible. The less specific partition does
       not care for the order of b and c columns so it is valid if we sort
       by those in case of equality over a.

       partition by a, b; order by d, e      results in sorting by a b d e
       partition by a; order by e            results in sorting by a e

      This sorting is incompatible due to the order by clause. The partition by
      clause is compatible, (partition by a) is a prefix for (partition by a, b)
      However, order by e is not a prefix for order by d, e, thus it is not
      compatible.

    The rule for having compatible sorting is thus:
      Each partition order must contain the other window functions partitions
      prefixes, or be a prefix itself. This must hold true for all partitions.
      Analog for the order by clause.  
  */
#if 0
  List<Item_window_func> window_functions;
  SQL_I_List<ORDER> largest_partition;
  SQL_I_List<ORDER> largest_order_by;
  bool can_compute_window_live = !need_tmp;
  // Construct the window_functions item list and check if they can be
  // computed using only one sorting.
  //
  // TODO: Perhaps group functions into compatible sorting bins
  // to minimize the number of sorting passes required to compute all of them.
  while ((item= it++))
  {
    if (item->type() == Item::WINDOW_FUNC_ITEM)
    {
      Item_window_func *item_win = (Item_window_func *) item;
      window_functions.push_back(item_win);
      if (!can_compute_window_live)
        continue;  // No point checking  since we have to perform multiple sorts.
      Window_spec *spec = item_win->window_spec;
      // Having an empty partition list on one window function and a
      // not empty list on a separate window function causes the sorting
      // to be incompatible.
      //
      // Example:
      // over (partition by a, order by x) && over (order by x).
      //
      // The first function requires an ordering by a first and then by x,
      // while the seond function requires an ordering by x first.
      // The same restriction is not required for the order by clause.
      if (largest_partition.elements && !spec->partition_list.elements)
      {
        can_compute_window_live= FALSE;
        continue;
      }
      can_compute_window_live= test_if_order_compatible(largest_partition,
                                                        spec->partition_list);
      if (!can_compute_window_live)
        continue;

      can_compute_window_live= test_if_order_compatible(largest_order_by,
                                                        spec->order_list);
      if (!can_compute_window_live)
        continue;

      if (largest_partition.elements < spec->partition_list.elements)
        largest_partition = spec->partition_list;
      if (largest_order_by.elements < spec->order_list.elements)
        largest_order_by = spec->order_list;
    }
  }
  if (can_compute_window_live && window_functions.elements && table_count == 1)
  {
    ha_rows examined_rows = 0;
    ha_rows found_rows = 0;
    ha_rows filesort_retval;
    SORT_FIELD *s_order= (SORT_FIELD *) my_malloc(sizeof(SORT_FIELD) *
        (largest_partition.elements + largest_order_by.elements) + 1,
        MYF(MY_WME | MY_ZEROFILL | MY_THREAD_SPECIFIC));

    size_t pos= 0;
    for (ORDER* curr = largest_partition.first; curr; curr=curr->next, pos++)
      s_order[pos].item = *curr->item;

    for (ORDER* curr = largest_order_by.first; curr; curr=curr->next, pos++)
      s_order[pos].item = *curr->item;

    table[0]->sort.io_cache=(IO_CACHE*) my_malloc(sizeof(IO_CACHE),
                                               MYF(MY_WME | MY_ZEROFILL|
                                                   MY_THREAD_SPECIFIC));


    filesort_retval= filesort(thd, table[0], s_order,
                              (largest_partition.elements + largest_order_by.elements),
                              this->select, HA_POS_ERROR, FALSE,
                              &examined_rows, &found_rows,
                              this->explain->ops_tracker.report_sorting(thd));
    table[0]->sort.found_records= filesort_retval;

    join_tab->read_first_record = join_init_read_record;
    join_tab->records= found_rows;

    my_free(s_order);
  }
  else
#endif