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

#include "postgres.h"

#include "access/relation.h"
#include "access/table.h"
#include "access/tableam.h"
#include "catalog/partition.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_type.h"
#include "commands/tablecmds.h"
#include "common/hashfn.h"
#include "executor/executor.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/pathnodes.h"
#include "parser/parse_coerce.h"
#include "partitioning/partbounds.h"
#include "partitioning/partdesc.h"
#include "partitioning/partprune.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/partcache.h"
#include "utils/ruleutils.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"

/*
 * When qsort'ing partition bounds after reading from the catalog, each bound
 * is represented with one of the following structs.
 */

/* One bound of a hash partition */
typedef struct PartitionHashBound
{
	int			modulus;
	int			remainder;
	int			index;
} PartitionHashBound;

/* One value coming from some (index'th) list partition */
typedef struct PartitionListValue
{
	int			index;
	Datum		value;
} PartitionListValue;

/* One bound of a range partition */
typedef struct PartitionRangeBound
{
	int			index;
	Datum	   *datums;			/* range bound datums */
	PartitionRangeDatumKind *kind;	/* the kind of each datum */
	bool		lower;			/* this is the lower (vs upper) bound */
} PartitionRangeBound;

/*
 * Mapping from partitions of a joining relation to partitions of a join
 * relation being computed (a.k.a merged partitions)
 */
typedef struct PartitionMap
{
	int			nparts;			/* number of partitions */
	int		   *merged_indexes; /* indexes of merged partitions */
	bool	   *merged;			/* flags to indicate whether partitions are
								 * merged with non-dummy partitions */
	bool		did_remapping;	/* did we re-map partitions? */
	int		   *old_indexes;	/* old indexes of merged partitions if
								 * did_remapping */
} PartitionMap;

/* Macro for comparing two range bounds */
#define compare_range_bounds(partnatts, partsupfunc, partcollations, \
							 bound1, bound2) \
	(partition_rbound_cmp(partnatts, partsupfunc, partcollations, \
						  (bound1)->datums, (bound1)->kind, (bound1)->lower, \
						  bound2))

static int32 qsort_partition_hbound_cmp(const void *a, const void *b);
static int32 qsort_partition_list_value_cmp(const void *a, const void *b,
											void *arg);
static int32 qsort_partition_rbound_cmp(const void *a, const void *b,
										void *arg);
static PartitionBoundInfo create_hash_bounds(PartitionBoundSpec **boundspecs,
											 int nparts, PartitionKey key, int **mapping);
static PartitionBoundInfo create_list_bounds(PartitionBoundSpec **boundspecs,
											 int nparts, PartitionKey key, int **mapping);
static PartitionBoundInfo create_range_bounds(PartitionBoundSpec **boundspecs,
											  int nparts, PartitionKey key, int **mapping);
static PartitionBoundInfo merge_list_bounds(FmgrInfo *partsupfunc,
											Oid *collations,
											RelOptInfo *outer_rel,
											RelOptInfo *inner_rel,
											JoinType jointype,
											List **outer_parts,
											List **inner_parts);
static PartitionBoundInfo merge_range_bounds(int partnatts,
											 FmgrInfo *partsupfuncs,
											 Oid *partcollations,
											 RelOptInfo *outer_rel,
											 RelOptInfo *inner_rel,
											 JoinType jointype,
											 List **outer_parts,
											 List **inner_parts);
static void init_partition_map(RelOptInfo *rel, PartitionMap *map);
static void free_partition_map(PartitionMap *map);
static bool is_dummy_partition(RelOptInfo *rel, int part_index);
static int	merge_matching_partitions(PartitionMap *outer_map,
									  PartitionMap *inner_map,
									  int outer_part,
									  int inner_part,
									  int *next_index);
static int	process_outer_partition(PartitionMap *outer_map,
									PartitionMap *inner_map,
									bool outer_has_default,
									bool inner_has_default,
									int outer_index,
									int inner_default,
									JoinType jointype,
									int *next_index,
									int *default_index);
static int	process_inner_partition(PartitionMap *outer_map,
									PartitionMap *inner_map,
									bool outer_has_default,
									bool inner_has_default,
									int inner_index,
									int outer_default,
									JoinType jointype,
									int *next_index,
									int *default_index);
static void merge_null_partitions(PartitionMap *outer_map,
								  PartitionMap *inner_map,
								  bool outer_has_null,
								  bool inner_has_null,
								  int outer_null,
								  int inner_null,
								  JoinType jointype,
								  int *next_index,
								  int *null_index);
static void merge_default_partitions(PartitionMap *outer_map,
									 PartitionMap *inner_map,
									 bool outer_has_default,
									 bool inner_has_default,
									 int outer_default,
									 int inner_default,
									 JoinType jointype,
									 int *next_index,
									 int *default_index);
static int	merge_partition_with_dummy(PartitionMap *map, int index,
									   int *next_index);
static void fix_merged_indexes(PartitionMap *outer_map,
							   PartitionMap *inner_map,
							   int nmerged, List *merged_indexes);
static void generate_matching_part_pairs(RelOptInfo *outer_rel,
										 RelOptInfo *inner_rel,
										 PartitionMap *outer_map,
										 PartitionMap *inner_map,
										 int nmerged,
										 List **outer_parts,
										 List **inner_parts);
static PartitionBoundInfo build_merged_partition_bounds(char strategy,
														List *merged_datums,
														List *merged_kinds,
														List *merged_indexes,
														int null_index,
														int default_index);
static int	get_range_partition(RelOptInfo *rel,
								PartitionBoundInfo bi,
								int *lb_pos,
								PartitionRangeBound *lb,
								PartitionRangeBound *ub);
static int	get_range_partition_internal(PartitionBoundInfo bi,
										 int *lb_pos,
										 PartitionRangeBound *lb,
										 PartitionRangeBound *ub);
static bool compare_range_partitions(int partnatts, FmgrInfo *partsupfuncs,
									 Oid *partcollations,
									 PartitionRangeBound *outer_lb,
									 PartitionRangeBound *outer_ub,
									 PartitionRangeBound *inner_lb,
									 PartitionRangeBound *inner_ub,
									 int *lb_cmpval, int *ub_cmpval);
static void get_merged_range_bounds(int partnatts, FmgrInfo *partsupfuncs,
									Oid *partcollations, JoinType jointype,
									PartitionRangeBound *outer_lb,
									PartitionRangeBound *outer_ub,
									PartitionRangeBound *inner_lb,
									PartitionRangeBound *inner_ub,
									int lb_cmpval, int ub_cmpval,
									PartitionRangeBound *merged_lb,
									PartitionRangeBound *merged_ub);
static void add_merged_range_bounds(int partnatts, FmgrInfo *partsupfuncs,
									Oid *partcollations,
									PartitionRangeBound *merged_lb,
									PartitionRangeBound *merged_ub,
									int merged_index,
									List **merged_datums,
									List **merged_kinds,
									List **merged_indexes);
static PartitionRangeBound *make_one_partition_rbound(PartitionKey key, int index,
													  List *datums, bool lower);
static int32 partition_hbound_cmp(int modulus1, int remainder1, int modulus2,
								  int remainder2);
static int32 partition_rbound_cmp(int partnatts, FmgrInfo *partsupfunc,
								  Oid *partcollation, Datum *datums1,
								  PartitionRangeDatumKind *kind1, bool lower1,
								  PartitionRangeBound *b2);
static int	partition_range_bsearch(int partnatts, FmgrInfo *partsupfunc,
									Oid *partcollation,
									PartitionBoundInfo boundinfo,
									PartitionRangeBound *probe, int32 *cmpval);
static Expr *make_partition_op_expr(PartitionKey key, int keynum,
									uint16 strategy, Expr *arg1, Expr *arg2);
static Oid	get_partition_operator(PartitionKey key, int col,
								   StrategyNumber strategy, bool *need_relabel);
static List *get_qual_for_hash(Relation parent, PartitionBoundSpec *spec);
static List *get_qual_for_list(Relation parent, PartitionBoundSpec *spec);
static List *get_qual_for_range(Relation parent, PartitionBoundSpec *spec,
								bool for_default);
static void get_range_key_properties(PartitionKey key, int keynum,
									 PartitionRangeDatum *ldatum,
									 PartitionRangeDatum *udatum,
									 ListCell **partexprs_item,
									 Expr **keyCol,
									 Const **lower_val, Const **upper_val);
static List *get_range_nulltest(PartitionKey key);

/*
 * get_qual_from_partbound
 *		Given a parser node for partition bound, return the list of executable
 *		expressions as partition constraint
 */
List *
get_qual_from_partbound(Relation parent, PartitionBoundSpec *spec)
{
	PartitionKey key = RelationGetPartitionKey(parent);
	List	   *my_qual = NIL;

	Assert(key != NULL);

	switch (key->strategy)
	{
		case PARTITION_STRATEGY_HASH:
			Assert(spec->strategy == PARTITION_STRATEGY_HASH);
			my_qual = get_qual_for_hash(parent, spec);
			break;

		case PARTITION_STRATEGY_LIST:
			Assert(spec->strategy == PARTITION_STRATEGY_LIST);
			my_qual = get_qual_for_list(parent, spec);
			break;

		case PARTITION_STRATEGY_RANGE:
			Assert(spec->strategy == PARTITION_STRATEGY_RANGE);
			my_qual = get_qual_for_range(parent, spec, false);
			break;

		default:
			elog(ERROR, "unexpected partition strategy: %d",
				 (int) key->strategy);
	}

	return my_qual;
}

/*
 *	partition_bounds_create
 *		Build a PartitionBoundInfo struct from a list of PartitionBoundSpec
 *		nodes
 *
 * This function creates a PartitionBoundInfo and fills the values of its
 * various members based on the input list.  Importantly, 'datums' array will
 * contain Datum representation of individual bounds (possibly after
 * de-duplication as in case of range bounds), sorted in a canonical order
 * defined by qsort_partition_* functions of respective partitioning methods.
 * 'indexes' array will contain as many elements as there are bounds (specific
 * exceptions to this rule are listed in the function body), which represent
 * the 0-based canonical positions of partitions.
 *
 * Upon return from this function, *mapping is set to an array of
 * list_length(boundspecs) elements, each of which maps the original index of
 * a partition to its canonical index.
 *
 * Note: The objects returned by this function are wholly allocated in the
 * current memory context.
 */
PartitionBoundInfo
partition_bounds_create(PartitionBoundSpec **boundspecs, int nparts,
						PartitionKey key, int **mapping)
{
	int			i;

	Assert(nparts > 0);

	/*
	 * For each partitioning method, we first convert the partition bounds
	 * from their parser node representation to the internal representation,
	 * along with any additional preprocessing (such as de-duplicating range
	 * bounds).  Resulting bound datums are then added to the 'datums' array
	 * in PartitionBoundInfo.  For each datum added, an integer indicating the
	 * canonical partition index is added to the 'indexes' array.
	 *
	 * For each bound, we remember its partition's position (0-based) in the
	 * original list to later map it to the canonical index.
	 */

	/*
	 * Initialize mapping array with invalid values, this is filled within
	 * each sub-routine below depending on the bound type.
	 */
	*mapping = (int *) palloc(sizeof(int) * nparts);
	for (i = 0; i < nparts; i++)
		(*mapping)[i] = -1;

	switch (key->strategy)
	{
		case PARTITION_STRATEGY_HASH:
			return create_hash_bounds(boundspecs, nparts, key, mapping);

		case PARTITION_STRATEGY_LIST:
			return create_list_bounds(boundspecs, nparts, key, mapping);

		case PARTITION_STRATEGY_RANGE:
			return create_range_bounds(boundspecs, nparts, key, mapping);

		default:
			elog(ERROR, "unexpected partition strategy: %d",
				 (int) key->strategy);
			break;
	}

	Assert(false);
	return NULL;				/* keep compiler quiet */
}

/*
 * create_hash_bounds
 *		Create a PartitionBoundInfo for a hash partitioned table
 */
static PartitionBoundInfo
create_hash_bounds(PartitionBoundSpec **boundspecs, int nparts,
				   PartitionKey key, int **mapping)
{
	PartitionBoundInfo boundinfo;
	PartitionHashBound *hbounds;
	int			i;
	int			greatest_modulus;
	Datum	   *boundDatums;

	boundinfo = (PartitionBoundInfoData *)
		palloc0(sizeof(PartitionBoundInfoData));
	boundinfo->strategy = key->strategy;
	/* No special hash partitions. */
	boundinfo->null_index = -1;
	boundinfo->default_index = -1;

	hbounds = (PartitionHashBound *)
		palloc(nparts * sizeof(PartitionHashBound));

	/* Convert from node to the internal representation */
	for (i = 0; i < nparts; i++)
	{
		PartitionBoundSpec *spec = boundspecs[i];

		if (spec->strategy != PARTITION_STRATEGY_HASH)
			elog(ERROR, "invalid strategy in partition bound spec");

		hbounds[i].modulus = spec->modulus;
		hbounds[i].remainder = spec->remainder;
		hbounds[i].index = i;
	}

	/* Sort all the bounds in ascending order */
	qsort(hbounds, nparts, sizeof(PartitionHashBound),
		  qsort_partition_hbound_cmp);

	/* After sorting, moduli are now stored in ascending order. */
	greatest_modulus = hbounds[nparts - 1].modulus;

	boundinfo->ndatums = nparts;
	boundinfo->datums = (Datum **) palloc0(nparts * sizeof(Datum *));
	boundinfo->kind = NULL;
	boundinfo->interleaved_parts = NULL;
	boundinfo->nindexes = greatest_modulus;
	boundinfo->indexes = (int *) palloc(greatest_modulus * sizeof(int));
	for (i = 0; i < greatest_modulus; i++)
		boundinfo->indexes[i] = -1;

	/*
	 * In the loop below, to save from allocating a series of small datum
	 * arrays, here we just allocate a single array and below we'll just
	 * assign a portion of this array per partition.
	 */
	boundDatums = (Datum *) palloc(nparts * 2 * sizeof(Datum));

	/*
	 * For hash partitioning, there are as many datums (modulus and remainder
	 * pairs) as there are partitions.  Indexes are simply values ranging from
	 * 0 to (nparts - 1).
	 */
	for (i = 0; i < nparts; i++)
	{
		int			modulus = hbounds[i].modulus;
		int			remainder = hbounds[i].remainder;

		boundinfo->datums[i] = &boundDatums[i * 2];
		boundinfo->datums[i][0] = Int32GetDatum(modulus);
		boundinfo->datums[i][1] = Int32GetDatum(remainder);

		while (remainder < greatest_modulus)
		{
			/* overlap? */
			Assert(boundinfo->indexes[remainder] == -1);
			boundinfo->indexes[remainder] = i;
			remainder += modulus;
		}

		(*mapping)[hbounds[i].index] = i;
	}
	pfree(hbounds);

	return boundinfo;
}

/*
 * get_non_null_list_datum_count
 * 		Counts the number of non-null Datums in each partition.
 */
static int
get_non_null_list_datum_count(PartitionBoundSpec **boundspecs, int nparts)
{
	int			i;
	int			count = 0;

	for (i = 0; i < nparts; i++)
	{
		ListCell   *lc;

		foreach(lc, boundspecs[i]->listdatums)
		{
			Const	   *val = lfirst_node(Const, lc);

			if (!val->constisnull)
				count++;
		}
	}

	return count;
}

/*
 * create_list_bounds
 *		Create a PartitionBoundInfo for a list partitioned table
 */
static PartitionBoundInfo
create_list_bounds(PartitionBoundSpec **boundspecs, int nparts,
				   PartitionKey key, int **mapping)
{
	PartitionBoundInfo boundinfo;
	PartitionListValue *all_values;
	int			i;
	int			j;
	int			ndatums;
	int			next_index = 0;
	int			default_index = -1;
	int			null_index = -1;
	Datum	   *boundDatums;

	boundinfo = (PartitionBoundInfoData *)
		palloc0(sizeof(PartitionBoundInfoData));
	boundinfo->strategy = key->strategy;
	/* Will be set correctly below. */
	boundinfo->null_index = -1;
	boundinfo->default_index = -1;

	ndatums = get_non_null_list_datum_count(boundspecs, nparts);
	all_values = (PartitionListValue *)
		palloc(ndatums * sizeof(PartitionListValue));

	/* Create a unified list of non-null values across all partitions. */
	for (j = 0, i = 0; i < nparts; i++)
	{
		PartitionBoundSpec *spec = boundspecs[i];
		ListCell   *c;

		if (spec->strategy != PARTITION_STRATEGY_LIST)
			elog(ERROR, "invalid strategy in partition bound spec");

		/*
		 * Note the index of the partition bound spec for the default
		 * partition.  There's no datum to add to the list on non-null datums
		 * for this partition.
		 */
		if (spec->is_default)
		{
			default_index = i;
			continue;
		}

		foreach(c, spec->listdatums)
		{
			Const	   *val = lfirst_node(Const, c);

			if (!val->constisnull)
			{
				all_values[j].index = i;
				all_values[j].value = val->constvalue;
				j++;
			}
			else
			{
				/*
				 * Never put a null into the values array; save the index of
				 * the partition that stores nulls, instead.
				 */
				if (null_index != -1)
					elog(ERROR, "found null more than once");
				null_index = i;
			}
		}
	}

	/* ensure we found a Datum for every slot in the all_values array */
	Assert(j == ndatums);

	qsort_arg(all_values, ndatums, sizeof(PartitionListValue),
			  qsort_partition_list_value_cmp, (void *) key);

	boundinfo->ndatums = ndatums;
	boundinfo->datums = (Datum **) palloc0(ndatums * sizeof(Datum *));
	boundinfo->kind = NULL;
	boundinfo->interleaved_parts = NULL;
	boundinfo->nindexes = ndatums;
	boundinfo->indexes = (int *) palloc(ndatums * sizeof(int));

	/*
	 * In the loop below, to save from allocating a series of small datum
	 * arrays, here we just allocate a single array and below we'll just
	 * assign a portion of this array per datum.
	 */
	boundDatums = (Datum *) palloc(ndatums * sizeof(Datum));

	/*
	 * Copy values.  Canonical indexes are values ranging from 0 to (nparts -
	 * 1) assigned to each partition such that all datums of a given partition
	 * receive the same value. The value for a given partition is the index of
	 * that partition's smallest datum in the all_values[] array.
	 */
	for (i = 0; i < ndatums; i++)
	{
		int			orig_index = all_values[i].index;

		boundinfo->datums[i] = &boundDatums[i];
		boundinfo->datums[i][0] = datumCopy(all_values[i].value,
											key->parttypbyval[0],
											key->parttyplen[0]);

		/* If the old index has no mapping, assign one */
		if ((*mapping)[orig_index] == -1)
			(*mapping)[orig_index] = next_index++;

		boundinfo->indexes[i] = (*mapping)[orig_index];
	}

	pfree(all_values);

	/*
	 * Set the canonical value for null_index, if any.
	 *
	 * It is possible that the null-accepting partition has not been assigned
	 * an index yet, which could happen if such partition accepts only null
	 * and hence not handled in the above loop which only looked at non-null
	 * values.
	 */
	if (null_index != -1)
	{
		Assert(null_index >= 0);
		if ((*mapping)[null_index] == -1)
			(*mapping)[null_index] = next_index++;
		boundinfo->null_index = (*mapping)[null_index];
	}

	/* Set the canonical value for default_index, if any. */
	if (default_index != -1)
	{
		/*
		 * The default partition accepts any value not specified in the lists
		 * of other partitions, hence it should not get mapped index while
		 * assigning those for non-null datums.
		 */
		Assert(default_index >= 0);
		Assert((*mapping)[default_index] == -1);
		(*mapping)[default_index] = next_index++;
		boundinfo->default_index = (*mapping)[default_index];
	}

	/*
	 * Calculate interleaved partitions.  Here we look for partitions which
	 * might be interleaved with other partitions and set a bit in
	 * interleaved_parts for any partitions which may be interleaved with
	 * another partition.
	 */

	/*
	 * There must be multiple partitions to have any interleaved partitions,
	 * otherwise there's nothing to interleave with.
	 */
	if (nparts > 1)
	{
		/*
		 * Short-circuit check to see if only 1 Datum is allowed per
		 * partition.  When this is true there's no need to do the more
		 * expensive checks to look for interleaved values.
		 */
		if (boundinfo->ndatums +
			partition_bound_accepts_nulls(boundinfo) +
			partition_bound_has_default(boundinfo) != nparts)
		{
			int			last_index = -1;

			/*
			 * Since the indexes array is sorted in Datum order, if any
			 * partitions are interleaved then it will show up by the
			 * partition indexes not being in ascending order.  Here we check
			 * for that and record all partitions that are out of order.
			 */
			for (i = 0; i < boundinfo->nindexes; i++)
			{
				int			index = boundinfo->indexes[i];

				if (index < last_index)
					boundinfo->interleaved_parts = bms_add_member(boundinfo->interleaved_parts,
																  index);

				/*
				 * Mark the NULL partition as interleaved if we find that it
				 * allows some other non-NULL Datum.
				 */
				if (partition_bound_accepts_nulls(boundinfo) &&
					index == boundinfo->null_index)
					boundinfo->interleaved_parts = bms_add_member(boundinfo->interleaved_parts,
																  boundinfo->null_index);

				last_index = index;
			}
		}

		/*
		 * The DEFAULT partition is the "catch-all" partition that can contain
		 * anything that does not belong to any other partition.  If there are
		 * any other partitions then the DEFAULT partition must be marked as
		 * interleaved.
		 */
		if (partition_bound_has_default(boundinfo))
			boundinfo->interleaved_parts = bms_add_member(boundinfo->interleaved_parts,
														  boundinfo->default_index);
	}


	/* All partitions must now have been assigned canonical indexes. */
	Assert(next_index == nparts);
	return boundinfo;
}

/*
 * create_range_bounds
 *		Create a PartitionBoundInfo for a range partitioned table
 */
static PartitionBoundInfo
create_range_bounds(PartitionBoundSpec **boundspecs, int nparts,
					PartitionKey key, int **mapping)
{
	PartitionBoundInfo boundinfo;
	PartitionRangeBound **rbounds = NULL;
	PartitionRangeBound **all_bounds,
			   *prev;
	int			i,
				k,
				partnatts;
	int			ndatums = 0;
	int			default_index = -1;
	int			next_index = 0;
	Datum	   *boundDatums;
	PartitionRangeDatumKind *boundKinds;

	boundinfo = (PartitionBoundInfoData *)
		palloc0(sizeof(PartitionBoundInfoData));
	boundinfo->strategy = key->strategy;
	/* There is no special null-accepting range partition. */
	boundinfo->null_index = -1;
	/* Will be set correctly below. */
	boundinfo->default_index = -1;

	all_bounds = (PartitionRangeBound **)
		palloc0(2 * nparts * sizeof(PartitionRangeBound *));

	/* Create a unified list of range bounds across all the partitions. */
	ndatums = 0;
	for (i = 0; i < nparts; i++)
	{
		PartitionBoundSpec *spec = boundspecs[i];
		PartitionRangeBound *lower,
				   *upper;

		if (spec->strategy != PARTITION_STRATEGY_RANGE)
			elog(ERROR, "invalid strategy in partition bound spec");

		/*
		 * Note the index of the partition bound spec for the default
		 * partition.  There's no datum to add to the all_bounds array for
		 * this partition.
		 */
		if (spec->is_default)
		{
			default_index = i;
			continue;
		}

		lower = make_one_partition_rbound(key, i, spec->lowerdatums, true);
		upper = make_one_partition_rbound(key, i, spec->upperdatums, false);
		all_bounds[ndatums++] = lower;
		all_bounds[ndatums++] = upper;
	}

	Assert(ndatums == nparts * 2 ||
		   (default_index != -1 && ndatums == (nparts - 1) * 2));

	/* Sort all the bounds in ascending order */
	qsort_arg(all_bounds, ndatums,
			  sizeof(PartitionRangeBound *),
			  qsort_partition_rbound_cmp,
			  (void *) key);

	/* Save distinct bounds from all_bounds into rbounds. */
	rbounds = (PartitionRangeBound **)
		palloc(ndatums * sizeof(PartitionRangeBound *));
	k = 0;
	prev = NULL;
	for (i = 0; i < ndatums; i++)
	{
		PartitionRangeBound *cur = all_bounds[i];
		bool		is_distinct = false;
		int			j;

		/* Is the current bound distinct from the previous one? */
		for (j = 0; j < key->partnatts; j++)
		{
			Datum		cmpval;

			if (prev == NULL || cur->kind[j] != prev->kind[j])
			{
				is_distinct = true;
				break;
			}

			/*
			 * If the bounds are both MINVALUE or MAXVALUE, stop now and treat
			 * them as equal, since any values after this point must be
			 * ignored.
			 */
			if (cur->kind[j] != PARTITION_RANGE_DATUM_VALUE)
				break;

			cmpval = FunctionCall2Coll(&key->partsupfunc[j],
									   key->partcollation[j],
									   cur->datums[j],
									   prev->datums[j]);
			if (DatumGetInt32(cmpval) != 0)
			{
				is_distinct = true;
				break;
			}
		}

		/*
		 * Only if the bound is distinct save it into a temporary array, i.e,
		 * rbounds which is later copied into boundinfo datums array.
		 */
		if (is_distinct)
			rbounds[k++] = all_bounds[i];

		prev = cur;
	}

	pfree(all_bounds);

	/* Update ndatums to hold the count of distinct datums. */
	ndatums = k;

	/*
	 * Add datums to boundinfo.  Canonical indexes are values ranging from 0
	 * to nparts - 1, assigned in that order to each partition's upper bound.
	 * For 'datums' elements that are lower bounds, there is -1 in the
	 * 'indexes' array to signify that no partition exists for the values less
	 * than such a bound and greater than or equal to the previous upper
	 * bound.
	 */
	boundinfo->ndatums = ndatums;
	boundinfo->datums = (Datum **) palloc0(ndatums * sizeof(Datum *));
	boundinfo->kind = (PartitionRangeDatumKind **)
		palloc(ndatums *
			   sizeof(PartitionRangeDatumKind *));
	boundinfo->interleaved_parts = NULL;

	/*
	 * For range partitioning, an additional value of -1 is stored as the last
	 * element of the indexes[] array.
	 */
	boundinfo->nindexes = ndatums + 1;
	boundinfo->indexes = (int *) palloc((ndatums + 1) * sizeof(int));

	/*
	 * In the loop below, to save from allocating a series of small arrays,
	 * here we just allocate a single array for Datums and another for
	 * PartitionRangeDatumKinds, below we'll just assign a portion of these
	 * arrays in each loop.
	 */
	partnatts = key->partnatts;
	boundDatums = (Datum *) palloc(ndatums * partnatts * sizeof(Datum));
	boundKinds = (PartitionRangeDatumKind *) palloc(ndatums * partnatts *
													sizeof(PartitionRangeDatumKind));

	for (i = 0; i < ndatums; i++)
	{
		int			j;

		boundinfo->datums[i] = &boundDatums[i * partnatts];
		boundinfo->kind[i] = &boundKinds[i * partnatts];
		for (j = 0; j < partnatts; j++)
		{
			if (rbounds[i]->kind[j] == PARTITION_RANGE_DATUM_VALUE)
				boundinfo->datums[i][j] =
					datumCopy(rbounds[i]->datums[j],
							  key->parttypbyval[j],
							  key->parttyplen[j]);
			boundinfo->kind[i][j] = rbounds[i]->kind[j];
		}

		/*
		 * There is no mapping for invalid indexes.
		 *
		 * Any lower bounds in the rbounds array have invalid indexes
		 * assigned, because the values between the previous bound (if there
		 * is one) and this (lower) bound are not part of the range of any
		 * existing partition.
		 */
		if (rbounds[i]->lower)
			boundinfo->indexes[i] = -1;
		else
		{
			int			orig_index = rbounds[i]->index;

			/* If the old index has no mapping, assign one */
			if ((*mapping)[orig_index] == -1)
				(*mapping)[orig_index] = next_index++;

			boundinfo->indexes[i] = (*mapping)[orig_index];
		}
	}

	pfree(rbounds);

	/* Set the canonical value for default_index, if any. */
	if (default_index != -1)
	{
		Assert(default_index >= 0 && (*mapping)[default_index] == -1);
		(*mapping)[default_index] = next_index++;
		boundinfo->default_index = (*mapping)[default_index];
	}

	/* The extra -1 element. */
	Assert(i == ndatums);
	boundinfo->indexes[i] = -1;

	/* All partitions must now have been assigned canonical indexes. */
	Assert(next_index == nparts);
	return boundinfo;
}

/*
 * Are two partition bound collections logically equal?
 *
 * Used in the keep logic of relcache.c (ie, in RelationClearRelation()).
 * This is also useful when b1 and b2 are bound collections of two separate
 * relations, respectively, because PartitionBoundInfo is a canonical
 * representation of partition bounds.
 */
bool
partition_bounds_equal(int partnatts, int16 *parttyplen, bool *parttypbyval,
					   PartitionBoundInfo b1, PartitionBoundInfo b2)
{
	int			i;

	if (b1->strategy != b2->strategy)
		return false;

	if (b1->ndatums != b2->ndatums)
		return false;

	if (b1->nindexes != b2->nindexes)
		return false;

	if (b1->null_index != b2->null_index)
		return false;

	if (b1->default_index != b2->default_index)
		return false;

	/* For all partition strategies, the indexes[] arrays have to match */
	for (i = 0; i < b1->nindexes; i++)
	{
		if (b1->indexes[i] != b2->indexes[i])
			return false;
	}

	/* Finally, compare the datums[] arrays */
	if (b1->strategy == PARTITION_STRATEGY_HASH)
	{
		/*
		 * We arrange the partitions in the ascending order of their moduli
		 * and remainders.  Also every modulus is factor of next larger
		 * modulus.  Therefore we can safely store index of a given partition
		 * in indexes array at remainder of that partition.  Also entries at
		 * (remainder + N * modulus) positions in indexes array are all same
		 * for (modulus, remainder) specification for any partition.  Thus the
		 * datums arrays from the given bounds are the same, if and only if
		 * their indexes arrays are the same.  So, it suffices to compare the
		 * indexes arrays.
		 *
		 * Nonetheless make sure that the bounds are indeed the same when the
		 * indexes match.  Hash partition bound stores modulus and remainder
		 * at b1->datums[i][0] and b1->datums[i][1] position respectively.
		 */
#ifdef USE_ASSERT_CHECKING
		for (i = 0; i < b1->ndatums; i++)
			Assert((b1->datums[i][0] == b2->datums[i][0] &&
					b1->datums[i][1] == b2->datums[i][1]));
#endif
	}
	else
	{
		for (i = 0; i < b1->ndatums; i++)
		{
			int			j;

			for (j = 0; j < partnatts; j++)
			{
				/* For range partitions, the bounds might not be finite. */
				if (b1->kind != NULL)
				{
					/* The different kinds of bound all differ from each other */
					if (b1->kind[i][j] != b2->kind[i][j])
						return false;

					/*
					 * Non-finite bounds are equal without further
					 * examination.
					 */
					if (b1->kind[i][j] != PARTITION_RANGE_DATUM_VALUE)
						continue;
				}

				/*
				 * Compare the actual values. Note that it would be both
				 * incorrect and unsafe to invoke the comparison operator
				 * derived from the partitioning specification here.  It would
				 * be incorrect because we want the relcache entry to be
				 * updated for ANY change to the partition bounds, not just
				 * those that the partitioning operator thinks are
				 * significant.  It would be unsafe because we might reach
				 * this code in the context of an aborted transaction, and an
				 * arbitrary partitioning operator might not be safe in that
				 * context.  datumIsEqual() should be simple enough to be
				 * safe.
				 */
				if (!datumIsEqual(b1->datums[i][j], b2->datums[i][j],
								  parttypbyval[j], parttyplen[j]))
					return false;
			}
		}
	}
	return true;
}

/*
 * Return a copy of given PartitionBoundInfo structure. The data types of bounds
 * are described by given partition key specification.
 *
 * Note: it's important that this function and its callees not do any catalog
 * access, nor anything else that would result in allocating memory other than
 * the returned data structure.  Since this is called in a long-lived context,
 * that would result in unwanted memory leaks.
 */
PartitionBoundInfo
partition_bounds_copy(PartitionBoundInfo src,
					  PartitionKey key)
{
	PartitionBoundInfo dest;
	int			i;
	int			ndatums;
	int			nindexes;
	int			partnatts;
	bool		hash_part;
	int			natts;
	Datum	   *boundDatums;

	dest = (PartitionBoundInfo) palloc(sizeof(PartitionBoundInfoData));

	dest->strategy = src->strategy;
	ndatums = dest->ndatums = src->ndatums;
	nindexes = dest->nindexes = src->nindexes;
	partnatts = key->partnatts;

	/* List partitioned tables have only a single partition key. */
	Assert(key->strategy != PARTITION_STRATEGY_LIST || partnatts == 1);

	dest->datums = (Datum **) palloc(sizeof(Datum *) * ndatums);

	if (src->kind != NULL)
	{
		PartitionRangeDatumKind *boundKinds;

		/* only RANGE partition should have a non-NULL kind */
		Assert(key->strategy == PARTITION_STRATEGY_RANGE);

		dest->kind = (PartitionRangeDatumKind **) palloc(ndatums *
														 sizeof(PartitionRangeDatumKind *));

		/*
		 * In the loop below, to save from allocating a series of small arrays
		 * for storing the PartitionRangeDatumKind, we allocate a single chunk
		 * here and use a smaller portion of it for each datum.
		 */
		boundKinds = (PartitionRangeDatumKind *) palloc(ndatums * partnatts *
														sizeof(PartitionRangeDatumKind));

		for (i = 0; i < ndatums; i++)
		{
			dest->kind[i] = &boundKinds[i * partnatts];
			memcpy(dest->kind[i], src->kind[i],
				   sizeof(PartitionRangeDatumKind) * partnatts);
		}
	}
	else
		dest->kind = NULL;

	/* copy interleaved partitions for LIST partitioned tables */
	dest->interleaved_parts = bms_copy(src->interleaved_parts);

	/*
	 * For hash partitioning, datums array will have two elements - modulus
	 * and remainder.
	 */
	hash_part = (key->strategy == PARTITION_STRATEGY_HASH);
	natts = hash_part ? 2 : partnatts;
	boundDatums = palloc(ndatums * natts * sizeof(Datum));

	for (i = 0; i < ndatums; i++)
	{
		int			j;

		dest->datums[i] = &boundDatums[i * natts];

		for (j = 0; j < natts; j++)
		{
			bool		byval;
			int			typlen;

			if (hash_part)
			{
				typlen = sizeof(int32); /* Always int4 */
				byval = true;	/* int4 is pass-by-value */
			}
			else
			{
				byval = key->parttypbyval[j];
				typlen = key->parttyplen[j];
			}

			if (dest->kind == NULL ||
				dest->kind[i][j] == PARTITION_RANGE_DATUM_VALUE)
				dest->datums[i][j] = datumCopy(src->datums[i][j],
											   byval, typlen);
		}
	}

	dest->indexes = (int *) palloc(sizeof(int) * nindexes);
	memcpy(dest->indexes, src->indexes, sizeof(int) * nindexes);

	dest->null_index = src->null_index;
	dest->default_index = src->default_index;

	return dest;
}

/*
 * partition_bounds_merge
 *		Check to see whether every partition of 'outer_rel' matches/overlaps
 *		one partition of 'inner_rel' at most, and vice versa; and if so, build
 *		and return the partition bounds for a join relation between the rels,
 *		generating two lists of the matching/overlapping partitions, which are
 *		returned to *outer_parts and *inner_parts respectively.
 *
 * The lists contain the same number of partitions, and the partitions at the
 * same positions in the lists indicate join pairs used for partitioned join.
 * If a partition on one side matches/overlaps multiple partitions on the other
 * side, this function returns NULL, setting *outer_parts and *inner_parts to
 * NIL.
 */
PartitionBoundInfo
partition_bounds_merge(int partnatts,
					   FmgrInfo *partsupfunc, Oid *partcollation,
					   RelOptInfo *outer_rel, RelOptInfo *inner_rel,
					   JoinType jointype,
					   List **outer_parts, List **inner_parts)
{
	/*
	 * Currently, this function is called only from try_partitionwise_join(),
	 * so the join type should be INNER, LEFT, FULL, SEMI, or ANTI.
	 */
	Assert(jointype == JOIN_INNER || jointype == JOIN_LEFT ||
		   jointype == JOIN_FULL || jointype == JOIN_SEMI ||
		   jointype == JOIN_ANTI);

	/* The partitioning strategies should be the same. */
	Assert(outer_rel->boundinfo->strategy == inner_rel->boundinfo->strategy);

	*outer_parts = *inner_parts = NIL;
	switch (outer_rel->boundinfo->strategy)
	{
		case PARTITION_STRATEGY_HASH:

			/*
			 * For hash partitioned tables, we currently support partitioned
			 * join only when they have exactly the same partition bounds.
			 *
			 * XXX: it might be possible to relax the restriction to support
			 * cases where hash partitioned tables have missing partitions
			 * and/or different moduli, but it's not clear if it would be
			 * useful to support the former case since it's unusual to have
			 * missing partitions.  On the other hand, it would be useful to
			 * support the latter case, but in that case, there is a high
			 * probability that a partition on one side will match multiple
			 * partitions on the other side, which is the scenario the current
			 * implementation of partitioned join can't handle.
			 */
			return NULL;

		case PARTITION_STRATEGY_LIST:
			return merge_list_bounds(partsupfunc,
									 partcollation,
									 outer_rel,
									 inner_rel,
									 jointype,
									 outer_parts,
									 inner_parts);

		case PARTITION_STRATEGY_RANGE:
			return merge_range_bounds(partnatts,
									  partsupfunc,
									  partcollation,
									  outer_rel,
									  inner_rel,
									  jointype,
									  outer_parts,
									  inner_parts);

		default:
			elog(ERROR, "unexpected partition strategy: %d",
				 (int) outer_rel->boundinfo->strategy);
			return NULL;		/* keep compiler quiet */
	}
}

/*
 * merge_list_bounds
 *		Create the partition bounds for a join relation between list
 *		partitioned tables, if possible
 *
 * In this function we try to find sets of matching partitions from both sides
 * by comparing list values stored in their partition bounds.  Since the list
 * values appear in the ascending order, an algorithm similar to merge join is
 * used for that.  If a partition on one side doesn't have a matching
 * partition on the other side, the algorithm tries to match it with the
 * default partition on the other side if any; if not, the algorithm tries to
 * match it with a dummy partition on the other side if it's on the
 * non-nullable side of an outer join.  Also, if both sides have the default
 * partitions, the algorithm tries to match them with each other.  We give up
 * if the algorithm finds a partition matching multiple partitions on the
 * other side, which is the scenario the current implementation of partitioned
 * join can't handle.
 */
static PartitionBoundInfo
merge_list_bounds(FmgrInfo *partsupfunc, Oid *partcollation,
				  RelOptInfo *outer_rel, RelOptInfo *inner_rel,
				  JoinType jointype,
				  List **outer_parts, List **inner_parts)
{
	PartitionBoundInfo merged_bounds = NULL;
	PartitionBoundInfo outer_bi = outer_rel->boundinfo;
	PartitionBoundInfo inner_bi = inner_rel->boundinfo;
	bool		outer_has_default = partition_bound_has_default(outer_bi);
	bool		inner_has_default = partition_bound_has_default(inner_bi);
	int			outer_default = outer_bi->default_index;
	int			inner_default = inner_bi->default_index;
	bool		outer_has_null = partition_bound_accepts_nulls(outer_bi);
	bool		inner_has_null = partition_bound_accepts_nulls(inner_bi);
	PartitionMap outer_map;
	PartitionMap inner_map;
	int			outer_pos;
	int			inner_pos;
	int			next_index = 0;
	int			null_index = -1;
	int			default_index = -1;
	List	   *merged_datums = NIL;
	List	   *merged_indexes = NIL;

	Assert(*outer_parts == NIL);
	Assert(*inner_parts == NIL);
	Assert(outer_bi->strategy == inner_bi->strategy &&
		   outer_bi->strategy == PARTITION_STRATEGY_LIST);
	/* List partitioning doesn't require kinds. */
	Assert(!outer_bi->kind && !inner_bi->kind);

	init_partition_map(outer_rel, &outer_map);
	init_partition_map(inner_rel, &inner_map);

	/*
	 * If the default partitions (if any) have been proven empty, deem them
	 * non-existent.
	 */
	if (outer_has_default && is_dummy_partition(outer_rel, outer_default))
		outer_has_default = false;
	if (inner_has_default && is_dummy_partition(inner_rel, inner_default))
		inner_has_default = false;

	/*
	 * Merge partitions from both sides.  In each iteration we compare a pair
	 * of list values, one from each side, and decide whether the
	 * corresponding partitions match or not.  If the two values match
	 * exactly, move to the next pair of list values, otherwise move to the
	 * next list value on the side with a smaller list value.
	 */
	outer_pos = inner_pos = 0;
	while (outer_pos < outer_bi->ndatums || inner_pos < inner_bi->ndatums)
	{
		int			outer_index = -1;
		int			inner_index = -1;
		Datum	   *outer_datums;
		Datum	   *inner_datums;
		int			cmpval;
		Datum	   *merged_datum = NULL;
		int			merged_index = -1;

		if (outer_pos < outer_bi->ndatums)
		{
			/*
			 * If the partition on the outer side has been proven empty,
			 * ignore it and move to the next datum on the outer side.
			 */
			outer_index = outer_bi->indexes[outer_pos];
			if (is_dummy_partition(outer_rel, outer_index))
			{
				outer_pos++;
				continue;
			}
		}
		if (inner_pos < inner_bi->ndatums)
		{
			/*
			 * If the partition on the inner side has been proven empty,
			 * ignore it and move to the next datum on the inner side.
			 */
			inner_index = inner_bi->indexes[inner_pos];
			if (is_dummy_partition(inner_rel, inner_index))
			{
				inner_pos++;
				continue;
			}
		}

		/* Get the list values. */
		outer_datums = outer_pos < outer_bi->ndatums ?
			outer_bi->datums[outer_pos] : NULL;
		inner_datums = inner_pos < inner_bi->ndatums ?
			inner_bi->datums[inner_pos] : NULL;

		/*
		 * We run this loop till both sides finish.  This allows us to avoid
		 * duplicating code to handle the remaining values on the side which
		 * finishes later.  For that we set the comparison parameter cmpval in
		 * such a way that it appears as if the side which finishes earlier
		 * has an extra value higher than any other value on the unfinished
		 * side. That way we advance the values on the unfinished side till
		 * all of its values are exhausted.
		 */
		if (outer_pos >= outer_bi->ndatums)
			cmpval = 1;
		else if (inner_pos >= inner_bi->ndatums)
			cmpval = -1;
		else
		{
			Assert(outer_datums != NULL && inner_datums != NULL);
			cmpval = DatumGetInt32(FunctionCall2Coll(&partsupfunc[0],
													 partcollation[0],
													 outer_datums[0],
													 inner_datums[0]));
		}

		if (cmpval == 0)
		{
			/* Two list values match exactly. */
			Assert(outer_pos < outer_bi->ndatums);
			Assert(inner_pos < inner_bi->ndatums);
			Assert(outer_index >= 0);
			Assert(inner_index >= 0);

			/*
			 * Try merging both partitions.  If successful, add the list value
			 * and index of the merged partition below.
			 */
			merged_index = merge_matching_partitions(&outer_map, &inner_map,
													 outer_index, inner_index,
													 &next_index);
			if (merged_index == -1)
				goto cleanup;

			merged_datum = outer_datums;

			/* Move to the next pair of list values. */
			outer_pos++;
			inner_pos++;
		}
		else if (cmpval < 0)
		{
			/* A list value missing from the inner side. */
			Assert(outer_pos < outer_bi->ndatums);

			/*
			 * If the inner side has the default partition, or this is an
			 * outer join, try to assign a merged partition to the outer
			 * partition (see process_outer_partition()).  Otherwise, the
			 * outer partition will not contribute to the result.
			 */
			if (inner_has_default || IS_OUTER_JOIN(jointype))
			{
				/* Get the outer partition. */
				outer_index = outer_bi->indexes[outer_pos];
				Assert(outer_index >= 0);
				merged_index = process_outer_partition(&outer_map,
													   &inner_map,
													   outer_has_default,
													   inner_has_default,
													   outer_index,
													   inner_default,
													   jointype,
													   &next_index,
													   &default_index);
				if (merged_index == -1)
					goto cleanup;
				merged_datum = outer_datums;
			}

			/* Move to the next list value on the outer side. */
			outer_pos++;
		}
		else
		{
			/* A list value missing from the outer side. */
			Assert(cmpval > 0);
			Assert(inner_pos < inner_bi->ndatums);

			/*
			 * If the outer side has the default partition, or this is a FULL
			 * join, try to assign a merged partition to the inner partition
			 * (see process_inner_partition()).  Otherwise, the inner
			 * partition will not contribute to the result.
			 */
			if (outer_has_default || jointype == JOIN_FULL)
			{
				/* Get the inner partition. */
				inner_index = inner_bi->indexes[inner_pos];
				Assert(inner_index >= 0);
				merged_index = process_inner_partition(&outer_map,
													   &inner_map,
													   outer_has_default,
													   inner_has_default,
													   inner_index,
													   outer_default,
													   jointype,
													   &next_index,
													   &default_index);
				if (merged_index == -1)
					goto cleanup;
				merged_datum = inner_datums;
			}

			/* Move to the next list value on the inner side. */
			inner_pos++;
		}

		/*
		 * If we assigned a merged partition, add the list value and index of
		 * the merged partition if appropriate.
		 */
		if (merged_index >= 0 && merged_index != default_index)
		{
			merged_datums = lappend(merged_datums, merged_datum);
			merged_indexes = lappend_int(merged_indexes, merged_index);
		}
	}

	/*
	 * If the NULL partitions (if any) have been proven empty, deem them
	 * non-existent.
	 */
	if (outer_has_null &&
		is_dummy_partition(outer_rel, outer_bi->null_index))
		outer_has_null = false;
	if (inner_has_null &&
		is_dummy_partition(inner_rel, inner_bi->null_index))
		inner_has_null = false;

	/* Merge the NULL partitions if any. */
	if (outer_has_null || inner_has_null)
		merge_null_partitions(&outer_map, &inner_map,
							  outer_has_null, inner_has_null,
							  outer_bi->null_index, inner_bi->null_index,
							  jointype, &next_index, &null_index);
	else
		Assert(null_index == -1);

	/* Merge the default partitions if any. */
	if (outer_has_default || inner_has_default)
		merge_default_partitions(&outer_map, &inner_map,
								 outer_has_default, inner_has_default,
								 outer_default, inner_default,
								 jointype, &next_index, &default_index);
	else
		Assert(default_index == -1);

	/* If we have merged partitions, create the partition bounds. */
	if (next_index > 0)
	{
		/* Fix the merged_indexes list if necessary. */
		if (outer_map.did_remapping || inner_map.did_remapping)
		{
			Assert(jointype == JOIN_FULL);
			fix_merged_indexes(&outer_map, &inner_map,
							   next_index, merged_indexes);
		}

		/* Use maps to match partitions from inputs. */
		generate_matching_part_pairs(outer_rel, inner_rel,
									 &outer_map, &inner_map,
									 next_index,
									 outer_parts, inner_parts);
		Assert(*outer_parts != NIL);
		Assert(*inner_parts != NIL);
		Assert(list_length(*outer_parts) == list_length(*inner_parts));
		Assert(list_length(*outer_parts) <= next_index);

		/* Make a PartitionBoundInfo struct to return. */
		merged_bounds = build_merged_partition_bounds(outer_bi->strategy,
													  merged_datums,
													  NIL,
													  merged_indexes,
													  null_index,
													  default_index);
		Assert(merged_bounds);
	}

cleanup:
	/* Free local memory before returning. */
	list_free(merged_datums);
	list_free(merged_indexes);
	free_partition_map(&outer_map);
	free_partition_map(&inner_map);

	return merged_bounds;
}

/*
 * merge_range_bounds
 *		Create the partition bounds for a join relation between range
 *		partitioned tables, if possible
 *
 * In this function we try to find sets of overlapping partitions from both
 * sides by comparing ranges stored in their partition bounds.  Since the
 * ranges appear in the ascending order, an algorithm similar to merge join is
 * used for that.  If a partition on one side doesn't have an overlapping
 * partition on the other side, the algorithm tries to match it with the
 * default partition on the other side if any; if not, the algorithm tries to
 * match it with a dummy partition on the other side if it's on the
 * non-nullable side of an outer join.  Also, if both sides have the default
 * partitions, the algorithm tries to match them with each other.  We give up
 * if the algorithm finds a partition overlapping multiple partitions on the
 * other side, which is the scenario the current implementation of partitioned
 * join can't handle.
 */
static PartitionBoundInfo
merge_range_bounds(int partnatts, FmgrInfo *partsupfuncs,
				   Oid *partcollations,
				   RelOptInfo *outer_rel, RelOptInfo *inner_rel,
				   JoinType jointype,
				   List **outer_parts, List **inner_parts)
{
	PartitionBoundInfo merged_bounds = NULL;
	PartitionBoundInfo outer_bi = outer_rel->boundinfo;
	PartitionBoundInfo inner_bi = inner_rel->boundinfo;
	bool		outer_has_default = partition_bound_has_default(outer_bi);
	bool		inner_has_default = partition_bound_has_default(inner_bi);
	int			outer_default = outer_bi->default_index;
	int			inner_default = inner_bi->default_index;
	PartitionMap outer_map;
	PartitionMap inner_map;
	int			outer_index;
	int			inner_index;
	int			outer_lb_pos;
	int			inner_lb_pos;
	PartitionRangeBound outer_lb;
	PartitionRangeBound outer_ub;
	PartitionRangeBound inner_lb;
	PartitionRangeBound inner_ub;
	int			next_index = 0;
	int			default_index = -1;
	List	   *merged_datums = NIL;
	List	   *merged_kinds = NIL;
	List	   *merged_indexes = NIL;

	Assert(*outer_parts == NIL);
	Assert(*inner_parts == NIL);
	Assert(outer_bi->strategy == inner_bi->strategy &&
		   outer_bi->strategy == PARTITION_STRATEGY_RANGE);

	init_partition_map(outer_rel, &outer_map);
	init_partition_map(inner_rel, &inner_map);

	/*
	 * If the default partitions (if any) have been proven empty, deem them
	 * non-existent.
	 */
	if (outer_has_default && is_dummy_partition(outer_rel, outer_default))
		outer_has_default = false;
	if (inner_has_default && is_dummy_partition(inner_rel, inner_default))
		inner_has_default = false;

	/*
	 * Merge partitions from both sides.  In each iteration we compare a pair
	 * of ranges, one from each side, and decide whether the corresponding
	 * partitions match or not.  If the two ranges overlap, move to the next
	 * pair of ranges, otherwise move to the next range on the side with a
	 * lower range.  outer_lb_pos/inner_lb_pos keep track of the positions of
	 * lower bounds in the datums arrays in the outer/inner
	 * PartitionBoundInfos respectively.
	 */
	outer_lb_pos = inner_lb_pos = 0;
	outer_index = get_range_partition(outer_rel, outer_bi, &outer_lb_pos,
									  &outer_lb, &outer_ub);
	inner_index = get_range_partition(inner_rel, inner_bi, &inner_lb_pos,
									  &inner_lb, &inner_ub);
	while (outer_index >= 0 || inner_index >= 0)
	{
		bool		overlap;
		int			ub_cmpval;
		int			lb_cmpval;
		PartitionRangeBound merged_lb = {-1, NULL, NULL, true};
		PartitionRangeBound merged_ub = {-1, NULL, NULL, false};
		int			merged_index = -1;

		/*
		 * We run this loop till both sides finish.  This allows us to avoid
		 * duplicating code to handle the remaining ranges on the side which
		 * finishes later.  For that we set the comparison parameter cmpval in
		 * such a way that it appears as if the side which finishes earlier
		 * has an extra range higher than any other range on the unfinished
		 * side. That way we advance the ranges on the unfinished side till
		 * all of its ranges are exhausted.
		 */
		if (outer_index == -1)
		{
			overlap = false;
			lb_cmpval = 1;
			ub_cmpval = 1;
		}
		else if (inner_index == -1)
		{
			overlap = false;
			lb_cmpval = -1;
			ub_cmpval = -1;
		}
		else
			overlap = compare_range_partitions(partnatts, partsupfuncs,
											   partcollations,
											   &outer_lb, &outer_ub,
											   &inner_lb, &inner_ub,
											   &lb_cmpval, &ub_cmpval);

		if (overlap)
		{
			/* Two ranges overlap; form a join pair. */

			PartitionRangeBound save_outer_ub;
			PartitionRangeBound save_inner_ub;

			/* Both partitions should not have been merged yet. */
			Assert(outer_index >= 0);
			Assert(outer_map.merged_indexes[outer_index] == -1 &&
				   outer_map.merged[outer_index] == false);
			Assert(inner_index >= 0);
			Assert(inner_map.merged_indexes[inner_index] == -1 &&
				   inner_map.merged[inner_index] == false);

			/*
			 * Get the index of the merged partition.  Both partitions aren't
			 * merged yet, so the partitions should be merged successfully.
			 */
			merged_index = merge_matching_partitions(&outer_map, &inner_map,
													 outer_index, inner_index,
													 &next_index);
			Assert(merged_index >= 0);

			/* Get the range bounds of the merged partition. */
			get_merged_range_bounds(partnatts, partsupfuncs,
									partcollations, jointype,
									&outer_lb, &outer_ub,
									&inner_lb, &inner_ub,
									lb_cmpval, ub_cmpval,
									&merged_lb, &merged_ub);

			/* Save the upper bounds of both partitions for use below. */
			save_outer_ub = outer_ub;
			save_inner_ub = inner_ub;

			/* Move to the next pair of ranges. */
			outer_index = get_range_partition(outer_rel, outer_bi, &outer_lb_pos,
											  &outer_lb, &outer_ub);
			inner_index = get_range_partition(inner_rel, inner_bi, &inner_lb_pos,
											  &inner_lb, &inner_ub);

			/*
			 * If the range of a partition on one side overlaps the range of
			 * the next partition on the other side, that will cause the
			 * partition on one side to match at least two partitions on the
			 * other side, which is the case that we currently don't support
			 * partitioned join for; give up.
			 */
			if (ub_cmpval > 0 && inner_index >= 0 &&
				compare_range_bounds(partnatts, partsupfuncs, partcollations,
									 &save_outer_ub, &inner_lb) > 0)
				goto cleanup;
			if (ub_cmpval < 0 && outer_index >= 0 &&
				compare_range_bounds(partnatts, partsupfuncs, partcollations,
									 &outer_lb, &save_inner_ub) < 0)
				goto cleanup;

			/*
			 * A row from a non-overlapping portion (if any) of a partition on
			 * one side might find its join partner in the default partition
			 * (if any) on the other side, causing the same situation as
			 * above; give up in that case.
			 */
			if ((outer_has_default && (lb_cmpval > 0 || ub_cmpval < 0)) ||
				(inner_has_default && (lb_cmpval < 0 || ub_cmpval > 0)))
				goto cleanup;
		}
		else if (ub_cmpval < 0)
		{
			/* A non-overlapping outer range. */

			/* The outer partition should not have been merged yet. */
			Assert(outer_index >= 0);
			Assert(outer_map.merged_indexes[outer_index] == -1 &&
				   outer_map.merged[outer_index] == false);

			/*
			 * If the inner side has the default partition, or this is an
			 * outer join, try to assign a merged partition to the outer
			 * partition (see process_outer_partition()).  Otherwise, the
			 * outer partition will not contribute to the result.
			 */
			if (inner_has_default || IS_OUTER_JOIN(jointype))
			{
				merged_index = process_outer_partition(&outer_map,
													   &inner_map,
													   outer_has_default,
													   inner_has_default,
													   outer_index,
													   inner_default,
													   jointype,
													   &next_index,
													   &default_index);
				if (merged_index == -1)
					goto cleanup;
				merged_lb = outer_lb;
				merged_ub = outer_ub;
			}

			/* Move to the next range on the outer side. */
			outer_index = get_range_partition(outer_rel, outer_bi, &outer_lb_pos,
											  &outer_lb, &outer_ub);
		}
		else
		{
			/* A non-overlapping inner range. */
			Assert(ub_cmpval > 0);

			/* The inner partition should not have been merged yet. */
			Assert(inner_index >= 0);
			Assert(inner_map.merged_indexes[inner_index] == -1 &&
				   inner_map.merged[inner_index] == false);

			/*
			 * If the outer side has the default partition, or this is a FULL
			 * join, try to assign a merged partition to the inner partition
			 * (see process_inner_partition()).  Otherwise, the inner
			 * partition will not contribute to the result.
			 */
			if (outer_has_default || jointype == JOIN_FULL)
			{
				merged_index = process_inner_partition(&outer_map,
													   &inner_map,
													   outer_has_default,
													   inner_has_default,
													   inner_index,
													   outer_default,
													   jointype,
													   &next_index,
													   &default_index);
				if (merged_index == -1)
					goto cleanup;
				merged_lb = inner_lb;
				merged_ub = inner_ub;
			}

			/* Move to the next range on the inner side. */
			inner_index = get_range_partition(inner_rel, inner_bi, &inner_lb_pos,
											  &inner_lb, &inner_ub);
		}

		/*
		 * If we assigned a merged partition, add the range bounds and index
		 * of the merged partition if appropriate.
		 */
		if (merged_index >= 0 && merged_index != default_index)
			add_merged_range_bounds(partnatts, partsupfuncs, partcollations,
									&merged_lb, &merged_ub, merged_index,
									&merged_datums, &merged_kinds,
									&merged_indexes);
	}

	/* Merge the default partitions if any. */
	if (outer_has_default || inner_has_default)
		merge_default_partitions(&outer_map, &inner_map,
								 outer_has_default, inner_has_default,
								 outer_default, inner_default,
								 jointype, &next_index, &default_index);
	else
		Assert(default_index == -1);

	/* If we have merged partitions, create the partition bounds. */
	if (next_index > 0)
	{
		/*
		 * Unlike the case of list partitioning, we wouldn't have re-merged
		 * partitions, so did_remapping should be left alone.
		 */
		Assert(!outer_map.did_remapping);
		Assert(!inner_map.did_remapping);

		/* Use maps to match partitions from inputs. */
		generate_matching_part_pairs(outer_rel, inner_rel,
									 &outer_map, &inner_map,
									 next_index,
									 outer_parts, inner_parts);
		Assert(*outer_parts != NIL);
		Assert(*inner_parts != NIL);
		Assert(list_length(*outer_parts) == list_length(*inner_parts));
		Assert(list_length(*outer_parts) == next_index);

		/* Make a PartitionBoundInfo struct to return. */
		merged_bounds = build_merged_partition_bounds(outer_bi->strategy,
													  merged_datums,
													  merged_kinds,
													  merged_indexes,
													  -1,
													  default_index);
		Assert(merged_bounds);
	}

cleanup:
	/* Free local memory before returning. */
	list_free(merged_datums);
	list_free(merged_kinds);
	list_free(merged_indexes);
	free_partition_map(&outer_map);
	free_partition_map(&inner_map);

	return merged_bounds;
}

/*
 * init_partition_map
 *		Initialize a PartitionMap struct for given relation
 */
static void
init_partition_map(RelOptInfo *rel, PartitionMap *map)
{
	int			nparts = rel->nparts;
	int			i;

	map->nparts = nparts;
	map->merged_indexes = (int *) palloc(sizeof(int) * nparts);
	map->merged = (bool *) palloc(sizeof(bool) * nparts);
	map->did_remapping = false;
	map->old_indexes = (int *) palloc(sizeof(int) * nparts);
	for (i = 0; i < nparts; i++)
	{
		map->merged_indexes[i] = map->old_indexes[i] = -1;
		map->merged[i] = false;
	}
}

/*
 * free_partition_map
 */
static void
free_partition_map(PartitionMap *map)
{
	pfree(map->merged_indexes);
	pfree(map->merged);
	pfree(map->old_indexes);
}

/*
 * is_dummy_partition --- has partition been proven empty?
 */
static bool
is_dummy_partition(RelOptInfo *rel, int part_index)
{
	RelOptInfo *part_rel;

	Assert(part_index >= 0);
	part_rel = rel->part_rels[part_index];
	if (part_rel == NULL || IS_DUMMY_REL(part_rel))
		return true;
	return false;
}

/*
 * merge_matching_partitions
 *		Try to merge given outer/inner partitions, and return the index of a
 *		merged partition produced from them if successful, -1 otherwise
 *
 * If the merged partition is newly created, *next_index is incremented.
 */
static int
merge_matching_partitions(PartitionMap *outer_map, PartitionMap *inner_map,
						  int outer_index, int inner_index, int *next_index)
{
	int			outer_merged_index;
	int			inner_merged_index;
	bool		outer_merged;
	bool		inner_merged;

	Assert(outer_index >= 0 && outer_index < outer_map->nparts);
	outer_merged_index = outer_map->merged_indexes[outer_index];
	outer_merged = outer_map->merged[outer_index];
	Assert(inner_index >= 0 && inner_index < inner_map->nparts);
	inner_merged_index = inner_map->merged_indexes[inner_index];
	inner_merged = inner_map->merged[inner_index];

	/*
	 * Handle cases where we have already assigned a merged partition to each
	 * of the given partitions.
	 */
	if (outer_merged_index >= 0 && inner_merged_index >= 0)
	{
		/*
		 * If the merged partitions are the same, no need to do anything;
		 * return the index of the merged partitions.  Otherwise, if each of
		 * the given partitions has been merged with a dummy partition on the
		 * other side, re-map them to either of the two merged partitions.
		 * Otherwise, they can't be merged, so return -1.
		 */
		if (outer_merged_index == inner_merged_index)
		{
			Assert(outer_merged);
			Assert(inner_merged);
			return outer_merged_index;
		}
		if (!outer_merged && !inner_merged)
		{
			/*
			 * This can only happen for a list-partitioning case.  We re-map
			 * them to the merged partition with the smaller of the two merged
			 * indexes to preserve the property that the canonical order of
			 * list partitions is determined by the indexes assigned to the
			 * smallest list value of each partition.
			 */
			if (outer_merged_index < inner_merged_index)
			{
				outer_map->merged[outer_index] = true;
				inner_map->merged_indexes[inner_index] = outer_merged_index;
				inner_map->merged[inner_index] = true;
				inner_map->did_remapping = true;
				inner_map->old_indexes[inner_index] = inner_merged_index;
				return outer_merged_index;
			}
			else
			{
				inner_map->merged[inner_index] = true;
				outer_map->merged_indexes[outer_index] = inner_merged_index;
				outer_map->merged[outer_index] = true;
				outer_map->did_remapping = true;
				outer_map->old_indexes[outer_index] = outer_merged_index;
				return inner_merged_index;
			}
		}
		return -1;
	}

	/* At least one of the given partitions should not have yet been merged. */
	Assert(outer_merged_index == -1 || inner_merged_index == -1);

	/*
	 * If neither of them has been merged, merge them.  Otherwise, if one has
	 * been merged with a dummy partition on the other side (and the other
	 * hasn't yet been merged with anything), re-merge them.  Otherwise, they
	 * can't be merged, so return -1.
	 */
	if (outer_merged_index == -1 && inner_merged_index == -1)
	{
		int			merged_index = *next_index;

		Assert(!outer_merged);
		Assert(!inner_merged);
		outer_map->merged_indexes[outer_index] = merged_index;
		outer_map->merged[outer_index] = true;
		inner_map->merged_indexes[inner_index] = merged_index;
		inner_map->merged[inner_index] = true;
		*next_index = *next_index + 1;
		return merged_index;
	}
	if (outer_merged_index >= 0 && !outer_map->merged[outer_index])
	{
		Assert(inner_merged_index == -1);
		Assert(!inner_merged);
		inner_map->merged_indexes[inner_index] = outer_merged_index;
		inner_map->merged[inner_index] = true;
		outer_map->merged[outer_index] = true;
		return outer_merged_index;
	}
	if (inner_merged_index >= 0 && !inner_map->merged[inner_index])
	{
		Assert(outer_merged_index == -1);
		Assert(!outer_merged);
		outer_map->merged_indexes[outer_index] = inner_merged_index;
		outer_map->merged[outer_index] = true;
		inner_map->merged[inner_index] = true;
		return inner_merged_index;
	}
	return -1;
}

/*
 * process_outer_partition
 *		Try to assign given outer partition a merged partition, and return the
 *		index of the merged partition if successful, -1 otherwise
 *
 * If the partition is newly created, *next_index is incremented.  Also, if it
 * is the default partition of the join relation, *default_index is set to the
 * index if not already done.
 */
static int
process_outer_partition(PartitionMap *outer_map,
						PartitionMap *inner_map,
						bool outer_has_default,
						bool inner_has_default,
						int outer_index,
						int inner_default,
						JoinType jointype,
						int *next_index,
						int *default_index)
{
	int			merged_index = -1;

	Assert(outer_index >= 0);

	/*
	 * If the inner side has the default partition, a row from the outer
	 * partition might find its join partner in the default partition; try
	 * merging the outer partition with the default partition.  Otherwise,
	 * this should be an outer join, in which case the outer partition has to
	 * be scanned all the way anyway; merge the outer partition with a dummy
	 * partition on the other side.
	 */
	if (inner_has_default)
	{
		Assert(inner_default >= 0);

		/*
		 * If the outer side has the default partition as well, the default
		 * partition on the inner side will have two matching partitions on
		 * the other side: the outer partition and the default partition on
		 * the outer side.  Partitionwise join doesn't handle this scenario
		 * yet.
		 */
		if (outer_has_default)
			return -1;

		merged_index = merge_matching_partitions(outer_map, inner_map,
												 outer_index, inner_default,
												 next_index);
		if (merged_index == -1)
			return -1;

		/*
		 * If this is a FULL join, the default partition on the inner side has
		 * to be scanned all the way anyway, so the resulting partition will
		 * contain all key values from the default partition, which any other
		 * partition of the join relation will not contain.  Thus the
		 * resulting partition will act as the default partition of the join
		 * relation; record the index in *default_index if not already done.
		 */
		if (jointype == JOIN_FULL)
		{
			if (*default_index == -1)
				*default_index = merged_index;
			else
				Assert(*default_index == merged_index);
		}
	}
	else
	{
		Assert(IS_OUTER_JOIN(jointype));
		Assert(jointype != JOIN_RIGHT);

		/* If we have already assigned a partition, no need to do anything. */
		merged_index = outer_map->merged_indexes[outer_index];
		if (merged_index == -1)
			merged_index = merge_partition_with_dummy(outer_map, outer_index,
													  next_index);
	}
	return merged_index;
}

/*
 * process_inner_partition
 *		Try to assign given inner partition a merged partition, and return the
 *		index of the merged partition if successful, -1 otherwise
 *
 * If the partition is newly created, *next_index is incremented.  Also, if it
 * is the default partition of the join relation, *default_index is set to the
 * index if not already done.
 */
static int
process_inner_partition(PartitionMap *outer_map,
						PartitionMap *inner_map,
						bool outer_has_default,
						bool inner_has_default,
						int inner_index,
						int outer_default,
						JoinType jointype,
						int *next_index,
						int *default_index)
{
	int			merged_index = -1;

	Assert(inner_index >= 0);

	/*
	 * If the outer side has the default partition, a row from the inner
	 * partition might find its join partner in the default partition; try
	 * merging the inner partition with the default partition.  Otherwise,
	 * this should be a FULL join, in which case the inner partition has to be
	 * scanned all the way anyway; merge the inner partition with a dummy
	 * partition on the other side.
	 */
	if (outer_has_default)
	{
		Assert(outer_default >= 0);

		/*
		 * If the inner side has the default partition as well, the default
		 * partition on the outer side will have two matching partitions on
		 * the other side: the inner partition and the default partition on
		 * the inner side.  Partitionwise join doesn't handle this scenario
		 * yet.
		 */
		if (inner_has_default)
			return -1;

		merged_index = merge_matching_partitions(outer_map, inner_map,
												 outer_default, inner_index,
												 next_index);
		if (merged_index == -1)
			return -1;

		/*
		 * If this is an outer join, the default partition on the outer side
		 * has to be scanned all the way anyway, so the resulting partition
		 * will contain all key values from the default partition, which any
		 * other partition of the join relation will not contain.  Thus the
		 * resulting partition will act as the default partition of the join
		 * relation; record the index in *default_index if not already done.
		 */
		if (IS_OUTER_JOIN(jointype))
		{
			Assert(jointype != JOIN_RIGHT);
			if (*default_index == -1)
				*default_index = merged_index;
			else
				Assert(*default_index == merged_index);
		}
	}
	else
	{
		Assert(jointype == JOIN_FULL);

		/* If we have already assigned a partition, no need to do anything. */
		merged_index = inner_map->merged_indexes[inner_index];
		if (merged_index == -1)
			merged_index = merge_partition_with_dummy(inner_map, inner_index,
													  next_index);
	}
	return merged_index;
}

/*
 * merge_null_partitions
 *		Merge the NULL partitions from a join's outer and inner sides.
 *
 * If the merged partition produced from them is the NULL partition of the join
 * relation, *null_index is set to the index of the merged partition.
 *
 * Note: We assume here that the join clause for a partitioned join is strict
 * because have_partkey_equi_join() requires that the corresponding operator
 * be mergejoinable, and we currently assume that mergejoinable operators are
 * strict (see MJEvalOuterValues()/MJEvalInnerValues()).
 */
static void
merge_null_partitions(PartitionMap *outer_map,
					  PartitionMap *inner_map,
					  bool outer_has_null,
					  bool inner_has_null,
					  int outer_null,
					  int inner_null,
					  JoinType jointype,
					  int *next_index,
					  int *null_index)
{
	bool		consider_outer_null = false;
	bool		consider_inner_null = false;

	Assert(outer_has_null || inner_has_null);
	Assert(*null_index == -1);

	/*
	 * Check whether the NULL partitions have already been merged and if so,
	 * set the consider_outer_null/consider_inner_null flags.
	 */
	if (outer_has_null)
	{
		Assert(outer_null >= 0 && outer_null < outer_map->nparts);
		if (outer_map->merged_indexes[outer_null] == -1)
			consider_outer_null = true;
	}
	if (inner_has_null)
	{
		Assert(inner_null >= 0 && inner_null < inner_map->nparts);
		if (inner_map->merged_indexes[inner_null] == -1)
			consider_inner_null = true;
	}

	/* If both flags are set false, we don't need to do anything. */
	if (!consider_outer_null && !consider_inner_null)
		return;

	if (consider_outer_null && !consider_inner_null)
	{
		Assert(outer_has_null);

		/*
		 * If this is an outer join, the NULL partition on the outer side has
		 * to be scanned all the way anyway; merge the NULL partition with a
		 * dummy partition on the other side.  In that case
		 * consider_outer_null means that the NULL partition only contains
		 * NULL values as the key values, so the merged partition will do so;
		 * treat it as the NULL partition of the join relation.
		 */
		if (IS_OUTER_JOIN(jointype))
		{
			Assert(jointype != JOIN_RIGHT);
			*null_index = merge_partition_with_dummy(outer_map, outer_null,
													 next_index);
		}
	}
	else if (!consider_outer_null && consider_inner_null)
	{
		Assert(inner_has_null);

		/*
		 * If this is a FULL join, the NULL partition on the inner side has to
		 * be scanned all the way anyway; merge the NULL partition with a
		 * dummy partition on the other side.  In that case
		 * consider_inner_null means that the NULL partition only contains
		 * NULL values as the key values, so the merged partition will do so;
		 * treat it as the NULL partition of the join relation.
		 */
		if (jointype == JOIN_FULL)
			*null_index = merge_partition_with_dummy(inner_map, inner_null,
													 next_index);
	}
	else
	{
		Assert(consider_outer_null && consider_inner_null);
		Assert(outer_has_null);
		Assert(inner_has_null);

		/*
		 * If this is an outer join, the NULL partition on the outer side (and
		 * that on the inner side if this is a FULL join) have to be scanned
		 * all the way anyway, so merge them.  Note that each of the NULL
		 * partitions isn't merged yet, so they should be merged successfully.
		 * Like the above, each of the NULL partitions only contains NULL
		 * values as the key values, so the merged partition will do so; treat
		 * it as the NULL partition of the join relation.
		 *
		 * Note: if this an INNER/SEMI join, the join clause will never be
		 * satisfied by two NULL values (see comments above), so both the NULL
		 * partitions can be eliminated.
		 */
		if (IS_OUTER_JOIN(jointype))
		{
			Assert(jointype != JOIN_RIGHT);
			*null_index = merge_matching_partitions(outer_map, inner_map,
													outer_null, inner_null,
													next_index);
			Assert(*null_index >= 0);
		}
	}
}

/*
 * merge_default_partitions
 *		Merge the default partitions from a join's outer and inner sides.
 *
 * If the merged partition produced from them is the default partition of the
 * join relation, *default_index is set to the index of the merged partition.
 */
static void
merge_default_partitions(PartitionMap *outer_map,
						 PartitionMap *inner_map,
						 bool outer_has_default,
						 bool inner_has_default,
						 int outer_default,
						 int inner_default,
						 JoinType jointype,
						 int *next_index,
						 int *default_index)
{
	int			outer_merged_index = -1;
	int			inner_merged_index = -1;

	Assert(outer_has_default || inner_has_default);

	/* Get the merged partition indexes for the default partitions. */
	if (outer_has_default)
	{
		Assert(outer_default >= 0 && outer_default < outer_map->nparts);
		outer_merged_index = outer_map->merged_indexes[outer_default];
	}
	if (inner_has_default)
	{
		Assert(inner_default >= 0 && inner_default < inner_map->nparts);
		inner_merged_index = inner_map->merged_indexes[inner_default];
	}

	if (outer_has_default && !inner_has_default)
	{
		/*
		 * If this is an outer join, the default partition on the outer side
		 * has to be scanned all the way anyway; if we have not yet assigned a
		 * partition, merge the default partition with a dummy partition on
		 * the other side.  The merged partition will act as the default
		 * partition of the join relation (see comments in
		 * process_inner_partition()).
		 */
		if (IS_OUTER_JOIN(jointype))
		{
			Assert(jointype != JOIN_RIGHT);
			if (outer_merged_index == -1)
			{
				Assert(*default_index == -1);
				*default_index = merge_partition_with_dummy(outer_map,
															outer_default,
															next_index);
			}
			else
				Assert(*default_index == outer_merged_index);
		}
		else
			Assert(*default_index == -1);
	}
	else if (!outer_has_default && inner_has_default)
	{
		/*
		 * If this is a FULL join, the default partition on the inner side has
		 * to be scanned all the way anyway; if we have not yet assigned a
		 * partition, merge the default partition with a dummy partition on
		 * the other side.  The merged partition will act as the default
		 * partition of the join relation (see comments in
		 * process_outer_partition()).
		 */
		if (jointype == JOIN_FULL)
		{
			if (inner_merged_index == -1)
			{
				Assert(*default_index == -1);
				*default_index = merge_partition_with_dummy(inner_map,
															inner_default,
															next_index);
			}
			else
				Assert(*default_index == inner_merged_index);
		}
		else
			Assert(*default_index == -1);
	}
	else
	{
		Assert(outer_has_default && inner_has_default);

		/*
		 * The default partitions have to be joined with each other, so merge
		 * them.  Note that each of the default partitions isn't merged yet
		 * (see, process_outer_partition()/process_innerer_partition()), so
		 * they should be merged successfully.  The merged partition will act
		 * as the default partition of the join relation.
		 */
		Assert(outer_merged_index == -1);
		Assert(inner_merged_index == -1);
		Assert(*default_index == -1);
		*default_index = merge_matching_partitions(outer_map,
												   inner_map,
												   outer_default,
												   inner_default,
												   next_index);
		Assert(*default_index >= 0);
	}
}

/*
 * merge_partition_with_dummy
 *		Assign given partition a new partition of a join relation
 *
 * Note: The caller assumes that the given partition doesn't have a non-dummy
 * matching partition on the other side, but if the given partition finds the
 * matching partition later, we will adjust the assignment.
 */
static int
merge_partition_with_dummy(PartitionMap *map, int index, int *next_index)
{
	int			merged_index = *next_index;

	Assert(index >= 0 && index < map->nparts);
	Assert(map->merged_indexes[index] == -1);
	Assert(!map->merged[index]);
	map->merged_indexes[index] = merged_index;
	/* Leave the merged flag alone! */
	*next_index = *next_index + 1;
	return merged_index;
}

/*
 * fix_merged_indexes
 *		Adjust merged indexes of re-merged partitions
 */
static void
fix_merged_indexes(PartitionMap *outer_map, PartitionMap *inner_map,
				   int nmerged, List *merged_indexes)
{
	int		   *new_indexes;
	int			merged_index;
	int			i;
	ListCell   *lc;

	Assert(nmerged > 0);

	new_indexes = (int *) palloc(sizeof(int) * nmerged);
	for (i = 0; i < nmerged; i++)
		new_indexes[i] = -1;

	/* Build the mapping of old merged indexes to new merged indexes. */
	if (outer_map->did_remapping)
	{
		for (i = 0; i < outer_map->nparts; i++)
		{
			merged_index = outer_map->old_indexes[i];
			if (merged_index >= 0)
				new_indexes[merged_index] = outer_map->merged_indexes[i];
		}
	}
	if (inner_map->did_remapping)
	{
		for (i = 0; i < inner_map->nparts; i++)
		{
			merged_index = inner_map->old_indexes[i];
			if (merged_index >= 0)
				new_indexes[merged_index] = inner_map->merged_indexes[i];
		}
	}

	/* Fix the merged_indexes list using the mapping. */
	foreach(lc, merged_indexes)
	{
		merged_index = lfirst_int(lc);
		Assert(merged_index >= 0);
		if (new_indexes[merged_index] >= 0)
			lfirst_int(lc) = new_indexes[merged_index];
	}

	pfree(new_indexes);
}

/*
 * generate_matching_part_pairs
 *		Generate a pair of lists of partitions that produce merged partitions
 *
 * The lists of partitions are built in the order of merged partition indexes,
 * and returned in *outer_parts and *inner_parts.
 */
static void
generate_matching_part_pairs(RelOptInfo *outer_rel, RelOptInfo *inner_rel,
							 PartitionMap *outer_map, PartitionMap *inner_map,
							 int nmerged,
							 List **outer_parts, List **inner_parts)
{
	int			outer_nparts = outer_map->nparts;
	int			inner_nparts = inner_map->nparts;
	int		   *outer_indexes;
	int		   *inner_indexes;
	int			max_nparts;
	int			i;

	Assert(nmerged > 0);
	Assert(*outer_parts == NIL);
	Assert(*inner_parts == NIL);

	outer_indexes = (int *) palloc(sizeof(int) * nmerged);
	inner_indexes = (int *) palloc(sizeof(int) * nmerged);
	for (i = 0; i < nmerged; i++)
		outer_indexes[i] = inner_indexes[i] = -1;

	/* Set pairs of matching partitions. */
	Assert(outer_nparts == outer_rel->nparts);
	Assert(inner_nparts == inner_rel->nparts);
	max_nparts = Max(outer_nparts, inner_nparts);
	for (i = 0; i < max_nparts; i++)
	{
		if (i < outer_nparts)
		{
			int			merged_index = outer_map->merged_indexes[i];

			if (merged_index >= 0)
			{
				Assert(merged_index < nmerged);
				outer_indexes[merged_index] = i;
			}
		}
		if (i < inner_nparts)
		{
			int			merged_index = inner_map->merged_indexes[i];

			if (merged_index >= 0)
			{
				Assert(merged_index < nmerged);
				inner_indexes[merged_index] = i;
			}
		}
	}

	/* Build the list pairs. */
	for (i = 0; i < nmerged; i++)
	{
		int			outer_index = outer_indexes[i];
		int			inner_index = inner_indexes[i];

		/*
		 * If both partitions are dummy, it means the merged partition that
		 * had been assigned to the outer/inner partition was removed when
		 * re-merging the outer/inner partition in
		 * merge_matching_partitions(); ignore the merged partition.
		 */
		if (outer_index == -1 && inner_index == -1)
			continue;

		*outer_parts = lappend(*outer_parts, outer_index >= 0 ?
							   outer_rel->part_rels[outer_index] : NULL);
		*inner_parts = lappend(*inner_parts, inner_index >= 0 ?
							   inner_rel->part_rels[inner_index] : NULL);
	}

	pfree(outer_indexes);
	pfree(inner_indexes);
}

/*
 * build_merged_partition_bounds
 *		Create a PartitionBoundInfo struct from merged partition bounds
 */
static PartitionBoundInfo
build_merged_partition_bounds(char strategy, List *merged_datums,
							  List *merged_kinds, List *merged_indexes,
							  int null_index, int default_index)
{
	PartitionBoundInfo merged_bounds;
	int			ndatums = list_length(merged_datums);
	int			pos;
	ListCell   *lc;

	merged_bounds = (PartitionBoundInfo) palloc(sizeof(PartitionBoundInfoData));
	merged_bounds->strategy = strategy;
	merged_bounds->ndatums = ndatums;

	merged_bounds->datums = (Datum **) palloc(sizeof(Datum *) * ndatums);
	pos = 0;
	foreach(lc, merged_datums)
		merged_bounds->datums[pos++] = (Datum *) lfirst(lc);

	if (strategy == PARTITION_STRATEGY_RANGE)
	{
		Assert(list_length(merged_kinds) == ndatums);
		merged_bounds->kind = (PartitionRangeDatumKind **)
			palloc(sizeof(PartitionRangeDatumKind *) * ndatums);
		pos = 0;
		foreach(lc, merged_kinds)
			merged_bounds->kind[pos++] = (PartitionRangeDatumKind *) lfirst(lc);

		/* There are ndatums+1 indexes in the case of range partitioning. */
		merged_indexes = lappend_int(merged_indexes, -1);
		ndatums++;
	}
	else
	{
		Assert(strategy == PARTITION_STRATEGY_LIST);
		Assert(merged_kinds == NIL);
		merged_bounds->kind = NULL;
	}

	/* interleaved_parts is always NULL for join relations. */
	merged_bounds->interleaved_parts = NULL;

	Assert(list_length(merged_indexes) == ndatums);
	merged_bounds->nindexes = ndatums;
	merged_bounds->indexes = (int *) palloc(sizeof(int) * ndatums);
	pos = 0;
	foreach(lc, merged_indexes)
		merged_bounds->indexes[pos++] = lfirst_int(lc);

	merged_bounds->null_index = null_index;
	merged_bounds->default_index = default_index;

	return merged_bounds;
}

/*
 * get_range_partition
 *		Get the next non-dummy partition of a range-partitioned relation,
 *		returning the index of that partition
 *
 * *lb and *ub are set to the lower and upper bounds of that partition
 * respectively, and *lb_pos is advanced to the next lower bound, if any.
 */
static int
get_range_partition(RelOptInfo *rel,
					PartitionBoundInfo bi,
					int *lb_pos,
					PartitionRangeBound *lb,
					PartitionRangeBound *ub)
{
	int			part_index;

	Assert(bi->strategy == PARTITION_STRATEGY_RANGE);

	do
	{
		part_index = get_range_partition_internal(bi, lb_pos, lb, ub);
		if (part_index == -1)
			return -1;
	} while (is_dummy_partition(rel, part_index));

	return part_index;
}

static int
get_range_partition_internal(PartitionBoundInfo bi,
							 int *lb_pos,
							 PartitionRangeBound *lb,
							 PartitionRangeBound *ub)
{
	/* Return the index as -1 if we've exhausted all lower bounds. */
	if (*lb_pos >= bi->ndatums)
		return -1;

	/* A lower bound should have at least one more bound after it. */
	Assert(*lb_pos + 1 < bi->ndatums);

	/* Set the lower bound. */
	lb->index = bi->indexes[*lb_pos];
	lb->datums = bi->datums[*lb_pos];
	lb->kind = bi->kind[*lb_pos];
	lb->lower = true;
	/* Set the upper bound. */
	ub->index = bi->indexes[*lb_pos + 1];
	ub->datums = bi->datums[*lb_pos + 1];
	ub->kind = bi->kind[*lb_pos + 1];
	ub->lower = false;

	/* The index assigned to an upper bound should be valid. */
	Assert(ub->index >= 0);

	/*
	 * Advance the position to the next lower bound.  If there are no bounds
	 * left beyond the upper bound, we have reached the last lower bound.
	 */
	if (*lb_pos + 2 >= bi->ndatums)
		*lb_pos = bi->ndatums;
	else
	{
		/*
		 * If the index assigned to the bound next to the upper bound isn't
		 * valid, that is the next lower bound; else, the upper bound is also
		 * the lower bound of the next range partition.
		 */
		if (bi->indexes[*lb_pos + 2] < 0)
			*lb_pos = *lb_pos + 2;
		else
			*lb_pos = *lb_pos + 1;
	}

	return ub->index;
}

/*
 * compare_range_partitions
 *		Compare the bounds of two range partitions, and return true if the
 *		two partitions overlap, false otherwise
 *
 * *lb_cmpval is set to -1, 0, or 1 if the outer partition's lower bound is
 * lower than, equal to, or higher than the inner partition's lower bound
 * respectively.  Likewise, *ub_cmpval is set to -1, 0, or 1 if the outer
 * partition's upper bound is lower than, equal to, or higher than the inner
 * partition's upper bound respectively.
 */
static bool
compare_range_partitions(int partnatts, FmgrInfo *partsupfuncs,
						 Oid *partcollations,
						 PartitionRangeBound *outer_lb,
						 PartitionRangeBound *outer_ub,
						 PartitionRangeBound *inner_lb,
						 PartitionRangeBound *inner_ub,
						 int *lb_cmpval, int *ub_cmpval)
{
	/*
	 * Check if the outer partition's upper bound is lower than the inner
	 * partition's lower bound; if so the partitions aren't overlapping.
	 */
	if (compare_range_bounds(partnatts, partsupfuncs, partcollations,
							 outer_ub, inner_lb) < 0)
	{
		*lb_cmpval = -1;
		*ub_cmpval = -1;
		return false;
	}

	/*
	 * Check if the outer partition's lower bound is higher than the inner
	 * partition's upper bound; if so the partitions aren't overlapping.
	 */
	if (compare_range_bounds(partnatts, partsupfuncs, partcollations,
							 outer_lb, inner_ub) > 0)
	{
		*lb_cmpval = 1;
		*ub_cmpval = 1;
		return false;
	}

	/* All other cases indicate overlapping partitions. */
	*lb_cmpval = compare_range_bounds(partnatts, partsupfuncs, partcollations,
									  outer_lb, inner_lb);
	*ub_cmpval = compare_range_bounds(partnatts, partsupfuncs, partcollations,
									  outer_ub, inner_ub);
	return true;
}

/*
 * get_merged_range_bounds
 *		Given the bounds of range partitions to be joined, determine the bounds
 *		of a merged partition produced from the range partitions
 *
 * *merged_lb and *merged_ub are set to the lower and upper bounds of the
 * merged partition.
 */
static void
get_merged_range_bounds(int partnatts, FmgrInfo *partsupfuncs,
						Oid *partcollations, JoinType jointype,
						PartitionRangeBound *outer_lb,
						PartitionRangeBound *outer_ub,
						PartitionRangeBound *inner_lb,
						PartitionRangeBound *inner_ub,
						int lb_cmpval, int ub_cmpval,
						PartitionRangeBound *merged_lb,
						PartitionRangeBound *merged_ub)
{
	Assert(compare_range_bounds(partnatts, partsupfuncs, partcollations,
								outer_lb, inner_lb) == lb_cmpval);
	Assert(compare_range_bounds(partnatts, partsupfuncs, partcollations,
								outer_ub, inner_ub) == ub_cmpval);

	switch (jointype)
	{
		case JOIN_INNER:
		case JOIN_SEMI:

			/*
			 * An INNER/SEMI join will have the rows that fit both sides, so
			 * the lower bound of the merged partition will be the higher of
			 * the two lower bounds, and the upper bound of the merged
			 * partition will be the lower of the two upper bounds.
			 */
			*merged_lb = (lb_cmpval > 0) ? *outer_lb : *inner_lb;
			*merged_ub = (ub_cmpval < 0) ? *outer_ub : *inner_ub;
			break;

		case JOIN_LEFT:
		case JOIN_ANTI:

			/*
			 * A LEFT/ANTI join will have all the rows from the outer side, so
			 * the bounds of the merged partition will be the same as the
			 * outer bounds.
			 */
			*merged_lb = *outer_lb;
			*merged_ub = *outer_ub;
			break;

		case JOIN_FULL:

			/*
			 * A FULL join will have all the rows from both sides, so the
			 * lower bound of the merged partition will be the lower of the
			 * two lower bounds, and the upper bound of the merged partition
			 * will be the higher of the two upper bounds.
			 */
			*merged_lb = (lb_cmpval < 0) ? *outer_lb : *inner_lb;
			*merged_ub = (ub_cmpval > 0) ? *outer_ub : *inner_ub;
			break;

		default:
			elog(ERROR, "unrecognized join type: %d", (int) jointype);
	}
}

/*
 * add_merged_range_bounds
 *		Add the bounds of a merged partition to the lists of range bounds
 */
static void
add_merged_range_bounds(int partnatts, FmgrInfo *partsupfuncs,
						Oid *partcollations,
						PartitionRangeBound *merged_lb,
						PartitionRangeBound *merged_ub,
						int merged_index,
						List **merged_datums,
						List **merged_kinds,
						List **merged_indexes)
{
	int			cmpval;

	if (!*merged_datums)
	{
		/* First merged partition */
		Assert(!*merged_kinds);
		Assert(!*merged_indexes);
		cmpval = 1;
	}
	else
	{
		PartitionRangeBound prev_ub;

		Assert(*merged_datums);
		Assert(*merged_kinds);
		Assert(*merged_indexes);

		/* Get the last upper bound. */
		prev_ub.index = llast_int(*merged_indexes);
		prev_ub.datums = (Datum *) llast(*merged_datums);
		prev_ub.kind = (PartitionRangeDatumKind *) llast(*merged_kinds);
		prev_ub.lower = false;

		/*
		 * We pass lower1 = false to partition_rbound_cmp() to prevent it from
		 * considering the last upper bound to be smaller than the lower bound
		 * of the merged partition when the values of the two range bounds
		 * compare equal.
		 */
		cmpval = partition_rbound_cmp(partnatts, partsupfuncs, partcollations,
									  merged_lb->datums, merged_lb->kind,
									  false, &prev_ub);
		Assert(cmpval >= 0);
	}

	/*
	 * If the lower bound is higher than the last upper bound, add the lower
	 * bound with the index as -1 indicating that that is a lower bound; else,
	 * the last upper bound will be reused as the lower bound of the merged
	 * partition, so skip this.
	 */
	if (cmpval > 0)
	{
		*merged_datums = lappend(*merged_datums, merged_lb->datums);
		*merged_kinds = lappend(*merged_kinds, merged_lb->kind);
		*merged_indexes = lappend_int(*merged_indexes, -1);
	}

	/* Add the upper bound and index of the merged partition. */
	*merged_datums = lappend(*merged_datums, merged_ub->datums);
	*merged_kinds = lappend(*merged_kinds, merged_ub->kind);
	*merged_indexes = lappend_int(*merged_indexes, merged_index);
}

/*
 * partitions_are_ordered
 *		Determine whether the partitions described by 'boundinfo' are ordered,
 *		that is partitions appearing earlier in the PartitionDesc sequence
 *		contain partition keys strictly less than those appearing later.
 *		Also, if NULL values are possible, they must come in the last
 *		partition defined in the PartitionDesc.  'live_parts' marks which
 *		partitions we should include when checking the ordering.  Partitions
 *		that do not appear in 'live_parts' are ignored.
 *
 * If out of order, or there is insufficient info to know the order,
 * then we return false.
 */
bool
partitions_are_ordered(PartitionBoundInfo boundinfo, Bitmapset *live_parts)
{
	Assert(boundinfo != NULL);

	switch (boundinfo->strategy)
	{
		case PARTITION_STRATEGY_RANGE:

			/*
			 * RANGE-type partitioning guarantees that the partitions can be
			 * scanned in the order that they're defined in the PartitionDesc
			 * to provide sequential, non-overlapping ranges of tuples.
			 * However, if a DEFAULT partition exists and it's contained
			 * within live_parts, then the partitions are not ordered.
			 */
			if (!partition_bound_has_default(boundinfo) ||
				!bms_is_member(boundinfo->default_index, live_parts))
				return true;
			break;

		case PARTITION_STRATEGY_LIST:

			/*
			 * LIST partitioned are ordered providing none of live_parts
			 * overlap with the partitioned table's interleaved partitions.
			 */
			if (!bms_overlap(live_parts, boundinfo->interleaved_parts))
				return true;

			break;
		default:
			/* HASH, or some other strategy */
			break;
	}

	return false;
}

/*
 * check_new_partition_bound
 *
 * Checks if the new partition's bound overlaps any of the existing partitions
 * of parent.  Also performs additional checks as necessary per strategy.
 */
void
check_new_partition_bound(char *relname, Relation parent,
						  PartitionBoundSpec *spec, ParseState *pstate)
{
	PartitionKey key = RelationGetPartitionKey(parent);
	PartitionDesc partdesc = RelationGetPartitionDesc(parent, false);
	PartitionBoundInfo boundinfo = partdesc->boundinfo;
	int			with = -1;
	bool		overlap = false;
	int			overlap_location = -1;

	if (spec->is_default)
	{
		/*
		 * The default partition bound never conflicts with any other
		 * partition's; if that's what we're attaching, the only possible
		 * problem is that one already exists, so check for that and we're
		 * done.
		 */
		if (boundinfo == NULL || !partition_bound_has_default(boundinfo))
			return;

		/* Default partition already exists, error out. */
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
				 errmsg("partition \"%s\" conflicts with existing default partition \"%s\"",
						relname, get_rel_name(partdesc->oids[boundinfo->default_index])),
				 parser_errposition(pstate, spec->location)));
	}

	switch (key->strategy)
	{
		case PARTITION_STRATEGY_HASH:
			{
				Assert(spec->strategy == PARTITION_STRATEGY_HASH);
				Assert(spec->remainder >= 0 && spec->remainder < spec->modulus);

				if (partdesc->nparts > 0)
				{
					int			greatest_modulus;
					int			remainder;
					int			offset;

					/*
					 * Check rule that every modulus must be a factor of the
					 * next larger modulus.  (For example, if you have a bunch
					 * of partitions that all have modulus 5, you can add a
					 * new partition with modulus 10 or a new partition with
					 * modulus 15, but you cannot add both a partition with
					 * modulus 10 and a partition with modulus 15, because 10
					 * is not a factor of 15.)  We need only check the next
					 * smaller and next larger existing moduli, relying on
					 * previous enforcement of this rule to be sure that the
					 * rest are in line.
					 */

					/*
					 * Get the greatest (modulus, remainder) pair contained in
					 * boundinfo->datums that is less than or equal to the
					 * (spec->modulus, spec->remainder) pair.
					 */
					offset = partition_hash_bsearch(boundinfo,
													spec->modulus,
													spec->remainder);
					if (offset < 0)
					{
						int			next_modulus;

						/*
						 * All existing moduli are greater or equal, so the
						 * new one must be a factor of the smallest one, which
						 * is first in the boundinfo.
						 */
						next_modulus = DatumGetInt32(boundinfo->datums[0][0]);
						if (next_modulus % spec->modulus != 0)
							ereport(ERROR,
									(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
									 errmsg("every hash partition modulus must be a factor of the next larger modulus"),
									 errdetail("The new modulus %d is not a factor of %d, the modulus of existing partition \"%s\".",
											   spec->modulus, next_modulus,
											   get_rel_name(partdesc->oids[0]))));
					}
					else
					{
						int			prev_modulus;

						/*
						 * We found the largest (modulus, remainder) pair less
						 * than or equal to the new one.  That modulus must be
						 * a divisor of, or equal to, the new modulus.
						 */
						prev_modulus = DatumGetInt32(boundinfo->datums[offset][0]);

						if (spec->modulus % prev_modulus != 0)
							ereport(ERROR,
									(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
									 errmsg("every hash partition modulus must be a factor of the next larger modulus"),
									 errdetail("The new modulus %d is not divisible by %d, the modulus of existing partition \"%s\".",
											   spec->modulus,
											   prev_modulus,
											   get_rel_name(partdesc->oids[offset]))));

						if (offset + 1 < boundinfo->ndatums)
						{
							int			next_modulus;

							/*
							 * Look at the next higher (modulus, remainder)
							 * pair.  That could have the same modulus and a
							 * larger remainder than the new pair, in which
							 * case we're good.  If it has a larger modulus,
							 * the new modulus must divide that one.
							 */
							next_modulus = DatumGetInt32(boundinfo->datums[offset + 1][0]);

							if (next_modulus % spec->modulus != 0)
								ereport(ERROR,
										(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
										 errmsg("every hash partition modulus must be a factor of the next larger modulus"),
										 errdetail("The new modulus %d is not a factor of %d, the modulus of existing partition \"%s\".",
												   spec->modulus, next_modulus,
												   get_rel_name(partdesc->oids[offset + 1]))));
						}
					}

					greatest_modulus = boundinfo->nindexes;
					remainder = spec->remainder;

					/*
					 * Normally, the lowest remainder that could conflict with
					 * the new partition is equal to the remainder specified
					 * for the new partition, but when the new partition has a
					 * modulus higher than any used so far, we need to adjust.
					 */
					if (remainder >= greatest_modulus)
						remainder = remainder % greatest_modulus;

					/* Check every potentially-conflicting remainder. */
					do
					{
						if (boundinfo->indexes[remainder] != -1)
						{
							overlap = true;
							overlap_location = spec->location;
							with = boundinfo->indexes[remainder];
							break;
						}
						remainder += spec->modulus;
					} while (remainder < greatest_modulus);
				}

				break;
			}

		case PARTITION_STRATEGY_LIST:
			{
				Assert(spec->strategy == PARTITION_STRATEGY_LIST);

				if (partdesc->nparts > 0)
				{
					ListCell   *cell;

					Assert(boundinfo &&
						   boundinfo->strategy == PARTITION_STRATEGY_LIST &&
						   (boundinfo->ndatums > 0 ||
							partition_bound_accepts_nulls(boundinfo) ||
							partition_bound_has_default(boundinfo)));

					foreach(cell, spec->listdatums)
					{
						Const	   *val = lfirst_node(Const, cell);

						overlap_location = val->location;
						if (!val->constisnull)
						{
							int			offset;
							bool		equal;

							offset = partition_list_bsearch(&key->partsupfunc[0],
															key->partcollation,
															boundinfo,
															val->constvalue,
															&equal);
							if (offset >= 0 && equal)
							{
								overlap = true;
								with = boundinfo->indexes[offset];
								break;
							}
						}
						else if (partition_bound_accepts_nulls(boundinfo))
						{
							overlap = true;
							with = boundinfo->null_index;
							break;
						}
					}
				}

				break;
			}

		case PARTITION_STRATEGY_RANGE:
			{
				PartitionRangeBound *lower,
						   *upper;
				int			cmpval;

				Assert(spec->strategy == PARTITION_STRATEGY_RANGE);
				lower = make_one_partition_rbound(key, -1, spec->lowerdatums, true);
				upper = make_one_partition_rbound(key, -1, spec->upperdatums, false);

				/*
				 * First check if the resulting range would be empty with
				 * specified lower and upper bounds.  partition_rbound_cmp
				 * cannot return zero here, since the lower-bound flags are
				 * different.
				 */
				cmpval = partition_rbound_cmp(key->partnatts,
											  key->partsupfunc,
											  key->partcollation,
											  lower->datums, lower->kind,
											  true, upper);
				Assert(cmpval != 0);
				if (cmpval > 0)
				{
					/* Point to problematic key in the lower datums list. */
					PartitionRangeDatum *datum = list_nth(spec->lowerdatums,
														  cmpval - 1);

					ereport(ERROR,
							(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
							 errmsg("empty range bound specified for partition \"%s\"",
									relname),
							 errdetail("Specified lower bound %s is greater than or equal to upper bound %s.",
									   get_range_partbound_string(spec->lowerdatums),
									   get_range_partbound_string(spec->upperdatums)),
							 parser_errposition(pstate, datum->location)));
				}

				if (partdesc->nparts > 0)
				{
					int			offset;

					Assert(boundinfo &&
						   boundinfo->strategy == PARTITION_STRATEGY_RANGE &&
						   (boundinfo->ndatums > 0 ||
							partition_bound_has_default(boundinfo)));

					/*
					 * Test whether the new lower bound (which is treated
					 * inclusively as part of the new partition) lies inside
					 * an existing partition, or in a gap.
					 *
					 * If it's inside an existing partition, the bound at
					 * offset + 1 will be the upper bound of that partition,
					 * and its index will be >= 0.
					 *
					 * If it's in a gap, the bound at offset + 1 will be the
					 * lower bound of the next partition, and its index will
					 * be -1. This is also true if there is no next partition,
					 * since the index array is initialised with an extra -1
					 * at the end.
					 */
					offset = partition_range_bsearch(key->partnatts,
													 key->partsupfunc,
													 key->partcollation,
													 boundinfo, lower,
													 &cmpval);

					if (boundinfo->indexes[offset + 1] < 0)
					{
						/*
						 * Check that the new partition will fit in the gap.
						 * For it to fit, the new upper bound must be less
						 * than or equal to the lower bound of the next
						 * partition, if there is one.
						 */
						if (offset + 1 < boundinfo->ndatums)
						{
							Datum	   *datums;
							PartitionRangeDatumKind *kind;
							bool		is_lower;

							datums = boundinfo->datums[offset + 1];
							kind = boundinfo->kind[offset + 1];
							is_lower = (boundinfo->indexes[offset + 1] == -1);

							cmpval = partition_rbound_cmp(key->partnatts,
														  key->partsupfunc,
														  key->partcollation,
														  datums, kind,
														  is_lower, upper);
							if (cmpval < 0)
							{
								/*
								 * Point to problematic key in the upper
								 * datums list.
								 */
								PartitionRangeDatum *datum =
								list_nth(spec->upperdatums, Abs(cmpval) - 1);

								/*
								 * The new partition overlaps with the
								 * existing partition between offset + 1 and
								 * offset + 2.
								 */
								overlap = true;
								overlap_location = datum->location;
								with = boundinfo->indexes[offset + 2];
							}
						}
					}
					else
					{
						/*
						 * The new partition overlaps with the existing
						 * partition between offset and offset + 1.
						 */
						PartitionRangeDatum *datum;

						/*
						 * Point to problematic key in the lower datums list;
						 * if we have equality, point to the first one.
						 */
						datum = cmpval == 0 ? linitial(spec->lowerdatums) :
							list_nth(spec->lowerdatums, Abs(cmpval) - 1);
						overlap = true;
						overlap_location = datum->location;
						with = boundinfo->indexes[offset + 1];
					}
				}

				break;
			}

		default:
			elog(ERROR, "unexpected partition strategy: %d",
				 (int) key->strategy);
	}

	if (overlap)
	{
		Assert(with >= 0);
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
				 errmsg("partition \"%s\" would overlap partition \"%s\"",
						relname, get_rel_name(partdesc->oids[with])),
				 parser_errposition(pstate, overlap_location)));
	}
}

/*
 * check_default_partition_contents
 *
 * This function checks if there exists a row in the default partition that
 * would properly belong to the new partition being added.  If it finds one,
 * it throws an error.
 */
void
check_default_partition_contents(Relation parent, Relation default_rel,
								 PartitionBoundSpec *new_spec)
{
	List	   *new_part_constraints;
	List	   *def_part_constraints;
	List	   *all_parts;
	ListCell   *lc;

	new_part_constraints = (new_spec->strategy == PARTITION_STRATEGY_LIST)
		? get_qual_for_list(parent, new_spec)
		: get_qual_for_range(parent, new_spec, false);
	def_part_constraints =
		get_proposed_default_constraint(new_part_constraints);

	/*
	 * Map the Vars in the constraint expression from parent's attnos to
	 * default_rel's.
	 */
	def_part_constraints =
		map_partition_varattnos(def_part_constraints, 1, default_rel,
								parent);

	/*
	 * If the existing constraints on the default partition imply that it will
	 * not contain any row that would belong to the new partition, we can
	 * avoid scanning the default partition.
	 */
	if (PartConstraintImpliedByRelConstraint(default_rel, def_part_constraints))
	{
		ereport(DEBUG1,
				(errmsg_internal("updated partition constraint for default partition \"%s\" is implied by existing constraints",
								 RelationGetRelationName(default_rel))));
		return;
	}

	/*
	 * Scan the default partition and its subpartitions, and check for rows
	 * that do not satisfy the revised partition constraints.
	 */
	if (default_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
		all_parts = find_all_inheritors(RelationGetRelid(default_rel),
										AccessExclusiveLock, NULL);
	else
		all_parts = list_make1_oid(RelationGetRelid(default_rel));

	foreach(lc, all_parts)
	{
		Oid			part_relid = lfirst_oid(lc);
		Relation	part_rel;
		Expr	   *partition_constraint;
		EState	   *estate;
		ExprState  *partqualstate = NULL;
		Snapshot	snapshot;
		ExprContext *econtext;
		TableScanDesc scan;
		MemoryContext oldCxt;
		TupleTableSlot *tupslot;

		/* Lock already taken above. */
		if (part_relid != RelationGetRelid(default_rel))
		{
			part_rel = table_open(part_relid, NoLock);

			/*
			 * Map the Vars in the constraint expression from default_rel's
			 * the sub-partition's.
			 */
			partition_constraint = make_ands_explicit(def_part_constraints);
			partition_constraint = (Expr *)
				map_partition_varattnos((List *) partition_constraint, 1,
										part_rel, default_rel);

			/*
			 * If the partition constraints on default partition child imply
			 * that it will not contain any row that would belong to the new
			 * partition, we can avoid scanning the child table.
			 */
			if (PartConstraintImpliedByRelConstraint(part_rel,
													 def_part_constraints))
			{
				ereport(DEBUG1,
						(errmsg_internal("updated partition constraint for default partition \"%s\" is implied by existing constraints",
										 RelationGetRelationName(part_rel))));

				table_close(part_rel, NoLock);
				continue;
			}
		}
		else
		{
			part_rel = default_rel;
			partition_constraint = make_ands_explicit(def_part_constraints);
		}

		/*
		 * Only RELKIND_RELATION relations (i.e. leaf partitions) need to be
		 * scanned.
		 */
		if (part_rel->rd_rel->relkind != RELKIND_RELATION)
		{
			if (part_rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
				ereport(WARNING,
						(errcode(ERRCODE_CHECK_VIOLATION),
						 errmsg("skipped scanning foreign table \"%s\" which is a partition of default partition \"%s\"",
								RelationGetRelationName(part_rel),
								RelationGetRelationName(default_rel))));

			if (RelationGetRelid(default_rel) != RelationGetRelid(part_rel))
				table_close(part_rel, NoLock);

			continue;
		}

		estate = CreateExecutorState();

		/* Build expression execution states for partition check quals */
		partqualstate = ExecPrepareExpr(partition_constraint, estate);

		econtext = GetPerTupleExprContext(estate);
		snapshot = RegisterSnapshot(GetLatestSnapshot());
		tupslot = table_slot_create(part_rel, &estate->es_tupleTable);
		scan = table_beginscan(part_rel, snapshot, 0, NULL);

		/*
		 * Switch to per-tuple memory context and reset it for each tuple
		 * produced, so we don't leak memory.
		 */
		oldCxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));

		while (table_scan_getnextslot(scan, ForwardScanDirection, tupslot))
		{
			econtext->ecxt_scantuple = tupslot;

			if (!ExecCheck(partqualstate, econtext))
				ereport(ERROR,
						(errcode(ERRCODE_CHECK_VIOLATION),
						 errmsg("updated partition constraint for default partition \"%s\" would be violated by some row",
								RelationGetRelationName(default_rel)),
						 errtable(default_rel)));

			ResetExprContext(econtext);
			CHECK_FOR_INTERRUPTS();
		}

		MemoryContextSwitchTo(oldCxt);
		table_endscan(scan);
		UnregisterSnapshot(snapshot);
		ExecDropSingleTupleTableSlot(tupslot);
		FreeExecutorState(estate);

		if (RelationGetRelid(default_rel) != RelationGetRelid(part_rel))
			table_close(part_rel, NoLock);	/* keep the lock until commit */
	}
}

/*
 * get_hash_partition_greatest_modulus
 *
 * Returns the greatest modulus of the hash partition bound.
 * This is no longer used in the core code, but we keep it around
 * in case external modules are using it.
 */
int
get_hash_partition_greatest_modulus(PartitionBoundInfo bound)
{
	Assert(bound && bound->strategy == PARTITION_STRATEGY_HASH);
	return bound->nindexes;
}

/*
 * make_one_partition_rbound
 *
 * Return a PartitionRangeBound given a list of PartitionRangeDatum elements
 * and a flag telling whether the bound is lower or not.  Made into a function
 * because there are multiple sites that want to use this facility.
 */
static PartitionRangeBound *
make_one_partition_rbound(PartitionKey key, int index, List *datums, bool lower)
{
	PartitionRangeBound *bound;
	ListCell   *lc;
	int			i;

	Assert(datums != NIL);

	bound = (PartitionRangeBound *) palloc0(sizeof(PartitionRangeBound));
	bound->index = index;
	bound->datums = (Datum *) palloc0(key->partnatts * sizeof(Datum));
	bound->kind = (PartitionRangeDatumKind *) palloc0(key->partnatts *
													  sizeof(PartitionRangeDatumKind));
	bound->lower = lower;

	i = 0;
	foreach(lc, datums)
	{
		PartitionRangeDatum *datum = lfirst_node(PartitionRangeDatum, lc);

		/* What's contained in this range datum? */
		bound->kind[i] = datum->kind;

		if (datum->kind == PARTITION_RANGE_DATUM_VALUE)
		{
			Const	   *val = castNode(Const, datum->value);

			if (val->constisnull)
				elog(ERROR, "invalid range bound datum");
			bound->datums[i] = val->constvalue;
		}

		i++;
	}

	return bound;
}

/*
 * partition_rbound_cmp
 *
 * For two range bounds this decides whether the 1st one (specified by
 * datums1, kind1, and lower1) is <, =, or > the bound specified in *b2.
 *
 * 0 is returned if they are equal, otherwise a non-zero integer whose sign
 * indicates the ordering, and whose absolute value gives the 1-based
 * partition key number of the first mismatching column.
 *
 * partnatts, partsupfunc and partcollation give the number of attributes in the
 * bounds to be compared, comparison function to be used and the collations of
 * attributes, respectively.
 *
 * Note that if the values of the two range bounds compare equal, then we take
 * into account whether they are upper or lower bounds, and an upper bound is
 * considered to be smaller than a lower bound. This is important to the way
 * that RelationBuildPartitionDesc() builds the PartitionBoundInfoData
 * structure, which only stores the upper bound of a common boundary between
 * two contiguous partitions.
 */
static int32
partition_rbound_cmp(int partnatts, FmgrInfo *partsupfunc,
					 Oid *partcollation,
					 Datum *datums1, PartitionRangeDatumKind *kind1,
					 bool lower1, PartitionRangeBound *b2)
{
	int32		colnum = 0;
	int32		cmpval = 0;		/* placate compiler */
	int			i;
	Datum	   *datums2 = b2->datums;
	PartitionRangeDatumKind *kind2 = b2->kind;
	bool		lower2 = b2->lower;

	for (i = 0; i < partnatts; i++)
	{
		/* Track column number in case we need it for result */
		colnum++;

		/*
		 * First, handle cases where the column is unbounded, which should not
		 * invoke the comparison procedure, and should not consider any later
		 * columns. Note that the PartitionRangeDatumKind enum elements
		 * compare the same way as the values they represent.
		 */
		if (kind1[i] < kind2[i])
			return -colnum;
		else if (kind1[i] > kind2[i])
			return colnum;
		else if (kind1[i] != PARTITION_RANGE_DATUM_VALUE)
		{
			/*
			 * The column bounds are both MINVALUE or both MAXVALUE. No later
			 * columns should be considered, but we still need to compare
			 * whether they are upper or lower bounds.
			 */
			break;
		}

		cmpval = DatumGetInt32(FunctionCall2Coll(&partsupfunc[i],
												 partcollation[i],
												 datums1[i],
												 datums2[i]));
		if (cmpval != 0)
			break;
	}

	/*
	 * If the comparison is anything other than equal, we're done. If they
	 * compare equal though, we still have to consider whether the boundaries
	 * are inclusive or exclusive.  Exclusive one is considered smaller of the
	 * two.
	 */
	if (cmpval == 0 && lower1 != lower2)
		cmpval = lower1 ? 1 : -1;

	return cmpval == 0 ? 0 : (cmpval < 0 ? -colnum : colnum);
}

/*
 * partition_rbound_datum_cmp
 *
 * Return whether range bound (specified in rb_datums and rb_kind)
 * is <, =, or > partition key of tuple (tuple_datums)
 *
 * n_tuple_datums, partsupfunc and partcollation give number of attributes in
 * the bounds to be compared, comparison function to be used and the collations
 * of attributes resp.
 */
int32
partition_rbound_datum_cmp(FmgrInfo *partsupfunc, Oid *partcollation,
						   Datum *rb_datums, PartitionRangeDatumKind *rb_kind,
						   Datum *tuple_datums, int n_tuple_datums)
{
	int			i;
	int32		cmpval = -1;

	for (i = 0; i < n_tuple_datums; i++)
	{
		if (rb_kind[i] == PARTITION_RANGE_DATUM_MINVALUE)
			return -1;
		else if (rb_kind[i] == PARTITION_RANGE_DATUM_MAXVALUE)
			return 1;

		cmpval = DatumGetInt32(FunctionCall2Coll(&partsupfunc[i],
												 partcollation[i],
												 rb_datums[i],
												 tuple_datums[i]));
		if (cmpval != 0)
			break;
	}

	return cmpval;
}

/*
 * partition_hbound_cmp
 *
 * Compares modulus first, then remainder if modulus is equal.
 */
static int32
partition_hbound_cmp(int modulus1, int remainder1, int modulus2, int remainder2)
{
	if (modulus1 < modulus2)
		return -1;
	if (modulus1 > modulus2)
		return 1;
	if (modulus1 == modulus2 && remainder1 != remainder2)
		return (remainder1 > remainder2) ? 1 : -1;
	return 0;
}

/*
 * partition_list_bsearch
 *		Returns the index of the greatest bound datum that is less than equal
 * 		to the given value or -1 if all of the bound datums are greater
 *
 * *is_equal is set to true if the bound datum at the returned index is equal
 * to the input value.
 */
int
partition_list_bsearch(FmgrInfo *partsupfunc, Oid *partcollation,
					   PartitionBoundInfo boundinfo,
					   Datum value, bool *is_equal)
{
	int			lo,
				hi,
				mid;

	lo = -1;
	hi = boundinfo->ndatums - 1;
	while (lo < hi)
	{
		int32		cmpval;

		mid = (lo + hi + 1) / 2;
		cmpval = DatumGetInt32(FunctionCall2Coll(&partsupfunc[0],
												 partcollation[0],
												 boundinfo->datums[mid][0],
												 value));
		if (cmpval <= 0)
		{
			lo = mid;
			*is_equal = (cmpval == 0);
			if (*is_equal)
				break;
		}
		else
			hi = mid - 1;
	}

	return lo;
}

/*
 * partition_range_bsearch
 *		Returns the index of the greatest range bound that is less than or
 *		equal to the given range bound or -1 if all of the range bounds are
 *		greater
 *
 * Upon return from this function, *cmpval is set to 0 if the bound at the
 * returned index matches the input range bound exactly, otherwise a
 * non-zero integer whose sign indicates the ordering, and whose absolute
 * value gives the 1-based partition key number of the first mismatching
 * column.
 */
static int
partition_range_bsearch(int partnatts, FmgrInfo *partsupfunc,
						Oid *partcollation,
						PartitionBoundInfo boundinfo,
						PartitionRangeBound *probe, int32 *cmpval)
{
	int			lo,
				hi,
				mid;

	lo = -1;
	hi = boundinfo->ndatums - 1;
	while (lo < hi)
	{
		mid = (lo + hi + 1) / 2;
		*cmpval = partition_rbound_cmp(partnatts, partsupfunc,
									   partcollation,
									   boundinfo->datums[mid],
									   boundinfo->kind[mid],
									   (boundinfo->indexes[mid] == -1),
									   probe);
		if (*cmpval <= 0)
		{
			lo = mid;
			if (*cmpval == 0)
				break;
		}
		else
			hi = mid - 1;
	}

	return lo;
}

/*
 * partition_range_datum_bsearch
 *		Returns the index of the greatest range bound that is less than or
 *		equal to the given tuple or -1 if all of the range bounds are greater
 *
 * *is_equal is set to true if the range bound at the returned index is equal
 * to the input tuple.
 */
int
partition_range_datum_bsearch(FmgrInfo *partsupfunc, Oid *partcollation,
							  PartitionBoundInfo boundinfo,
							  int nvalues, Datum *values, bool *is_equal)
{
	int			lo,
				hi,
				mid;

	lo = -1;
	hi = boundinfo->ndatums - 1;
	while (lo < hi)
	{
		int32		cmpval;

		mid = (lo + hi + 1) / 2;
		cmpval = partition_rbound_datum_cmp(partsupfunc,
											partcollation,
											boundinfo->datums[mid],
											boundinfo->kind[mid],
											values,
											nvalues);
		if (cmpval <= 0)
		{
			lo = mid;
			*is_equal = (cmpval == 0);

			if (*is_equal)
				break;
		}
		else
			hi = mid - 1;
	}

	return lo;
}

/*
 * partition_hash_bsearch
 *		Returns the index of the greatest (modulus, remainder) pair that is
 *		less than or equal to the given (modulus, remainder) pair or -1 if
 *		all of them are greater
 */
int
partition_hash_bsearch(PartitionBoundInfo boundinfo,
					   int modulus, int remainder)
{
	int			lo,
				hi,
				mid;

	lo = -1;
	hi = boundinfo->ndatums - 1;
	while (lo < hi)
	{
		int32		cmpval,
					bound_modulus,
					bound_remainder;

		mid = (lo + hi + 1) / 2;
		bound_modulus = DatumGetInt32(boundinfo->datums[mid][0]);
		bound_remainder = DatumGetInt32(boundinfo->datums[mid][1]);
		cmpval = partition_hbound_cmp(bound_modulus, bound_remainder,
									  modulus, remainder);
		if (cmpval <= 0)
		{
			lo = mid;

			if (cmpval == 0)
				break;
		}
		else
			hi = mid - 1;
	}

	return lo;
}

/*
 * qsort_partition_hbound_cmp
 *
 * Hash bounds are sorted by modulus, then by remainder.
 */
static int32
qsort_partition_hbound_cmp(const void *a, const void *b)
{
	PartitionHashBound *const h1 = (PartitionHashBound *const) a;
	PartitionHashBound *const h2 = (PartitionHashBound *const) b;

	return partition_hbound_cmp(h1->modulus, h1->remainder,
								h2->modulus, h2->remainder);
}

/*
 * qsort_partition_list_value_cmp
 *
 * Compare two list partition bound datums.
 */
static int32
qsort_partition_list_value_cmp(const void *a, const void *b, void *arg)
{
	Datum		val1 = ((PartitionListValue *const) a)->value,
				val2 = ((PartitionListValue *const) b)->value;
	PartitionKey key = (PartitionKey) arg;

	return DatumGetInt32(FunctionCall2Coll(&key->partsupfunc[0],
										   key->partcollation[0],
										   val1, val2));
}

/*
 * qsort_partition_rbound_cmp
 *
 * Used when sorting range bounds across all range partitions.
 */
static int32
qsort_partition_rbound_cmp(const void *a, const void *b, void *arg)
{
	PartitionRangeBound *b1 = (*(PartitionRangeBound *const *) a);
	PartitionRangeBound *b2 = (*(PartitionRangeBound *const *) b);
	PartitionKey key = (PartitionKey) arg;

	return compare_range_bounds(key->partnatts, key->partsupfunc,
								key->partcollation,
								b1, b2);
}

/*
 * get_partition_operator
 *
 * Return oid of the operator of the given strategy for the given partition
 * key column.  It is assumed that the partitioning key is of the same type as
 * the chosen partitioning opclass, or at least binary-compatible.  In the
 * latter case, *need_relabel is set to true if the opclass is not of a
 * polymorphic type (indicating a RelabelType node needed on top), otherwise
 * false.
 */
static Oid
get_partition_operator(PartitionKey key, int col, StrategyNumber strategy,
					   bool *need_relabel)
{
	Oid			operoid;

	/*
	 * Get the operator in the partitioning opfamily using the opclass'
	 * declared input type as both left- and righttype.
	 */
	operoid = get_opfamily_member(key->partopfamily[col],
								  key->partopcintype[col],
								  key->partopcintype[col],
								  strategy);
	if (!OidIsValid(operoid))
		elog(ERROR, "missing operator %d(%u,%u) in partition opfamily %u",
			 strategy, key->partopcintype[col], key->partopcintype[col],
			 key->partopfamily[col]);

	/*
	 * If the partition key column is not of the same type as the operator
	 * class and not polymorphic, tell caller to wrap the non-Const expression
	 * in a RelabelType.  This matches what parse_coerce.c does.
	 */
	*need_relabel = (key->parttypid[col] != key->partopcintype[col] &&
					 key->partopcintype[col] != RECORDOID &&
					 !IsPolymorphicType(key->partopcintype[col]));

	return operoid;
}

/*
 * make_partition_op_expr
 *		Returns an Expr for the given partition key column with arg1 and
 *		arg2 as its leftop and rightop, respectively
 */
static Expr *
make_partition_op_expr(PartitionKey key, int keynum,
					   uint16 strategy, Expr *arg1, Expr *arg2)
{
	Oid			operoid;
	bool		need_relabel = false;
	Expr	   *result = NULL;

	/* Get the correct btree operator for this partitioning column */
	operoid = get_partition_operator(key, keynum, strategy, &need_relabel);

	/*
	 * Chosen operator may be such that the non-Const operand needs to be
	 * coerced, so apply the same; see the comment in
	 * get_partition_operator().
	 */
	if (!IsA(arg1, Const) &&
		(need_relabel ||
		 key->partcollation[keynum] != key->parttypcoll[keynum]))
		arg1 = (Expr *) makeRelabelType(arg1,
										key->partopcintype[keynum],
										-1,
										key->partcollation[keynum],
										COERCE_EXPLICIT_CAST);

	/* Generate the actual expression */
	switch (key->strategy)
	{
		case PARTITION_STRATEGY_LIST:
			{
				List	   *elems = (List *) arg2;
				int			nelems = list_length(elems);

				Assert(nelems >= 1);
				Assert(keynum == 0);

				if (nelems > 1 &&
					!type_is_array(key->parttypid[keynum]))
				{
					ArrayExpr  *arrexpr;
					ScalarArrayOpExpr *saopexpr;

					/* Construct an ArrayExpr for the right-hand inputs */
					arrexpr = makeNode(ArrayExpr);
					arrexpr->array_typeid =
						get_array_type(key->parttypid[keynum]);
					arrexpr->array_collid = key->parttypcoll[keynum];
					arrexpr->element_typeid = key->parttypid[keynum];
					arrexpr->elements = elems;
					arrexpr->multidims = false;
					arrexpr->location = -1;

					/* Build leftop = ANY (rightop) */
					saopexpr = makeNode(ScalarArrayOpExpr);
					saopexpr->opno = operoid;
					saopexpr->opfuncid = get_opcode(operoid);
					saopexpr->hashfuncid = InvalidOid;
					saopexpr->negfuncid = InvalidOid;
					saopexpr->useOr = true;
					saopexpr->inputcollid = key->partcollation[keynum];
					saopexpr->args = list_make2(arg1, arrexpr);
					saopexpr->location = -1;

					result = (Expr *) saopexpr;
				}
				else
				{
					List	   *elemops = NIL;
					ListCell   *lc;

					foreach(lc, elems)
					{
						Expr	   *elem = lfirst(lc),
								   *elemop;

						elemop = make_opclause(operoid,
											   BOOLOID,
											   false,
											   arg1, elem,
											   InvalidOid,
											   key->partcollation[keynum]);
						elemops = lappend(elemops, elemop);
					}

					result = nelems > 1 ? makeBoolExpr(OR_EXPR, elemops, -1) : linitial(elemops);
				}
				break;
			}

		case PARTITION_STRATEGY_RANGE:
			result = make_opclause(operoid,
								   BOOLOID,
								   false,
								   arg1, arg2,
								   InvalidOid,
								   key->partcollation[keynum]);
			break;

		default:
			elog(ERROR, "invalid partitioning strategy");
			break;
	}

	return result;
}

/*
 * get_qual_for_hash
 *
 * Returns a CHECK constraint expression to use as a hash partition's
 * constraint, given the parent relation and partition bound structure.
 *
 * The partition constraint for a hash partition is always a call to the
 * built-in function satisfies_hash_partition().
 */
static List *
get_qual_for_hash(Relation parent, PartitionBoundSpec *spec)
{
	PartitionKey key = RelationGetPartitionKey(parent);
	FuncExpr   *fexpr;
	Node	   *relidConst;
	Node	   *modulusConst;
	Node	   *remainderConst;
	List	   *args;
	ListCell   *partexprs_item;
	int			i;

	/* Fixed arguments. */
	relidConst = (Node *) makeConst(OIDOID,
									-1,
									InvalidOid,
									sizeof(Oid),
									ObjectIdGetDatum(RelationGetRelid(parent)),
									false,
									true);

	modulusConst = (Node *) makeConst(INT4OID,
									  -1,
									  InvalidOid,
									  sizeof(int32),
									  Int32GetDatum(spec->modulus),
									  false,
									  true);

	remainderConst = (Node *) makeConst(INT4OID,
										-1,
										InvalidOid,
										sizeof(int32),
										Int32GetDatum(spec->remainder),
										false,
										true);

	args = list_make3(relidConst, modulusConst, remainderConst);
	partexprs_item = list_head(key->partexprs);

	/* Add an argument for each key column. */
	for (i = 0; i < key->partnatts; i++)
	{
		Node	   *keyCol;

		/* Left operand */
		if (key->partattrs[i] != 0)
		{
			keyCol = (Node *) makeVar(1,
									  key->partattrs[i],
									  key->parttypid[i],
									  key->parttypmod[i],
									  key->parttypcoll[i],
									  0);
		}
		else
		{
			keyCol = (Node *) copyObject(lfirst(partexprs_item));
			partexprs_item = lnext(key->partexprs, partexprs_item);
		}

		args = lappend(args, keyCol);
	}

	fexpr = makeFuncExpr(F_SATISFIES_HASH_PARTITION,
						 BOOLOID,
						 args,
						 InvalidOid,
						 InvalidOid,
						 COERCE_EXPLICIT_CALL);

	return list_make1(fexpr);
}

/*
 * get_qual_for_list
 *
 * Returns an implicit-AND list of expressions to use as a list partition's
 * constraint, given the parent relation and partition bound structure.
 *
 * The function returns NIL for a default partition when it's the only
 * partition since in that case there is no constraint.
 */
static List *
get_qual_for_list(Relation parent, PartitionBoundSpec *spec)
{
	PartitionKey key = RelationGetPartitionKey(parent);
	List	   *result;
	Expr	   *keyCol;
	Expr	   *opexpr;
	NullTest   *nulltest;
	ListCell   *cell;
	List	   *elems = NIL;
	bool		list_has_null = false;

	/*
	 * Only single-column list partitioning is supported, so we are worried
	 * only about the partition key with index 0.
	 */
	Assert(key->partnatts == 1);

	/* Construct Var or expression representing the partition column */
	if (key->partattrs[0] != 0)
		keyCol = (Expr *) makeVar(1,
								  key->partattrs[0],
								  key->parttypid[0],
								  key->parttypmod[0],
								  key->parttypcoll[0],
								  0);
	else
		keyCol = (Expr *) copyObject(linitial(key->partexprs));

	/*
	 * For default list partition, collect datums for all the partitions. The
	 * default partition constraint should check that the partition key is
	 * equal to none of those.
	 */
	if (spec->is_default)
	{
		int			i;
		int			ndatums = 0;
		PartitionDesc pdesc = RelationGetPartitionDesc(parent, false);
		PartitionBoundInfo boundinfo = pdesc->boundinfo;

		if (boundinfo)
		{
			ndatums = boundinfo->ndatums;

			if (partition_bound_accepts_nulls(boundinfo))
				list_has_null = true;
		}

		/*
		 * If default is the only partition, there need not be any partition
		 * constraint on it.
		 */
		if (ndatums == 0 && !list_has_null)
			return NIL;

		for (i = 0; i < ndatums; i++)
		{
			Const	   *val;

			/*
			 * Construct Const from known-not-null datum.  We must be careful
			 * to copy the value, because our result has to be able to outlive
			 * the relcache entry we're copying from.
			 */
			val = makeConst(key->parttypid[0],
							key->parttypmod[0],
							key->parttypcoll[0],
							key->parttyplen[0],
							datumCopy(*boundinfo->datums[i],
									  key->parttypbyval[0],
									  key->parttyplen[0]),
							false,	/* isnull */
							key->parttypbyval[0]);

			elems = lappend(elems, val);
		}
	}
	else
	{
		/*
		 * Create list of Consts for the allowed values, excluding any nulls.
		 */
		foreach(cell, spec->listdatums)
		{
			Const	   *val = lfirst_node(Const, cell);

			if (val->constisnull)
				list_has_null = true;
			else
				elems = lappend(elems, copyObject(val));
		}
	}

	if (elems)
	{
		/*
		 * Generate the operator expression from the non-null partition
		 * values.
		 */
		opexpr = make_partition_op_expr(key, 0, BTEqualStrategyNumber,
										keyCol, (Expr *) elems);
	}
	else
	{
		/*
		 * If there are no partition values, we don't need an operator
		 * expression.
		 */
		opexpr = NULL;
	}

	if (!list_has_null)
	{
		/*
		 * Gin up a "col IS NOT NULL" test that will be ANDed with the main
		 * expression.  This might seem redundant, but the partition routing
		 * machinery needs it.
		 */
		nulltest = makeNode(NullTest);
		nulltest->arg = keyCol;
		nulltest->nulltesttype = IS_NOT_NULL;
		nulltest->argisrow = false;
		nulltest->location = -1;

		result = opexpr ? list_make2(nulltest, opexpr) : list_make1(nulltest);
	}
	else
	{
		/*
		 * Gin up a "col IS NULL" test that will be OR'd with the main
		 * expression.
		 */
		nulltest = makeNode(NullTest);
		nulltest->arg = keyCol;
		nulltest->nulltesttype = IS_NULL;
		nulltest->argisrow = false;
		nulltest->location = -1;

		if (opexpr)
		{
			Expr	   *or;

			or = makeBoolExpr(OR_EXPR, list_make2(nulltest, opexpr), -1);
			result = list_make1(or);
		}
		else
			result = list_make1(nulltest);
	}

	/*
	 * Note that, in general, applying NOT to a constraint expression doesn't
	 * necessarily invert the set of rows it accepts, because NOT (NULL) is
	 * NULL.  However, the partition constraints we construct here never
	 * evaluate to NULL, so applying NOT works as intended.
	 */
	if (spec->is_default)
	{
		result = list_make1(make_ands_explicit(result));
		result = list_make1(makeBoolExpr(NOT_EXPR, result, -1));
	}

	return result;
}

/*
 * get_qual_for_range
 *
 * Returns an implicit-AND list of expressions to use as a range partition's
 * constraint, given the parent relation and partition bound structure.
 *
 * For a multi-column range partition key, say (a, b, c), with (al, bl, cl)
 * as the lower bound tuple and (au, bu, cu) as the upper bound tuple, we
 * generate an expression tree of the following form:
 *
 *	(a IS NOT NULL) and (b IS NOT NULL) and (c IS NOT NULL)
 *		AND
 *	(a > al OR (a = al AND b > bl) OR (a = al AND b = bl AND c >= cl))
 *		AND
 *	(a < au OR (a = au AND b < bu) OR (a = au AND b = bu AND c < cu))
 *
 * It is often the case that a prefix of lower and upper bound tuples contains
 * the same values, for example, (al = au), in which case, we will emit an
 * expression tree of the following form:
 *
 *	(a IS NOT NULL) and (b IS NOT NULL) and (c IS NOT NULL)
 *		AND
 *	(a = al)
 *		AND
 *	(b > bl OR (b = bl AND c >= cl))
 *		AND
 *	(b < bu OR (b = bu AND c < cu))
 *
 * If a bound datum is either MINVALUE or MAXVALUE, these expressions are
 * simplified using the fact that any value is greater than MINVALUE and less
 * than MAXVALUE. So, for example, if cu = MAXVALUE, c < cu is automatically
 * true, and we need not emit any expression for it, and the last line becomes
 *
 *	(b < bu) OR (b = bu), which is simplified to (b <= bu)
 *
 * In most common cases with only one partition column, say a, the following
 * expression tree will be generated: a IS NOT NULL AND a >= al AND a < au
 *
 * For default partition, it returns the negation of the constraints of all
 * the other partitions.
 *
 * External callers should pass for_default as false; we set it to true only
 * when recursing.
 */
static List *
get_qual_for_range(Relation parent, PartitionBoundSpec *spec,
				   bool for_default)
{
	List	   *result = NIL;
	ListCell   *cell1,
			   *cell2,
			   *partexprs_item,
			   *partexprs_item_saved;
	int			i,
				j;
	PartitionRangeDatum *ldatum,
			   *udatum;
	PartitionKey key = RelationGetPartitionKey(parent);
	Expr	   *keyCol;
	Const	   *lower_val,
			   *upper_val;
	List	   *lower_or_arms,
			   *upper_or_arms;
	int			num_or_arms,
				current_or_arm;
	ListCell   *lower_or_start_datum,
			   *upper_or_start_datum;
	bool		need_next_lower_arm,
				need_next_upper_arm;

	if (spec->is_default)
	{
		List	   *or_expr_args = NIL;
		PartitionDesc pdesc = RelationGetPartitionDesc(parent, false);
		Oid		   *inhoids = pdesc->oids;
		int			nparts = pdesc->nparts,
					i;

		for (i = 0; i < nparts; i++)
		{
			Oid			inhrelid = inhoids[i];
			HeapTuple	tuple;
			Datum		datum;
			bool		isnull;
			PartitionBoundSpec *bspec;

			tuple = SearchSysCache1(RELOID, inhrelid);
			if (!HeapTupleIsValid(tuple))
				elog(ERROR, "cache lookup failed for relation %u", inhrelid);

			datum = SysCacheGetAttr(RELOID, tuple,
									Anum_pg_class_relpartbound,
									&isnull);
			if (isnull)
				elog(ERROR, "null relpartbound for relation %u", inhrelid);

			bspec = (PartitionBoundSpec *)
				stringToNode(TextDatumGetCString(datum));
			if (!IsA(bspec, PartitionBoundSpec))
				elog(ERROR, "expected PartitionBoundSpec");

			if (!bspec->is_default)
			{
				List	   *part_qual;

				part_qual = get_qual_for_range(parent, bspec, true);

				/*
				 * AND the constraints of the partition and add to
				 * or_expr_args
				 */
				or_expr_args = lappend(or_expr_args, list_length(part_qual) > 1
									   ? makeBoolExpr(AND_EXPR, part_qual, -1)
									   : linitial(part_qual));
			}
			ReleaseSysCache(tuple);
		}

		if (or_expr_args != NIL)
		{
			Expr	   *other_parts_constr;

			/*
			 * Combine the constraints obtained for non-default partitions
			 * using OR.  As requested, each of the OR's args doesn't include
			 * the NOT NULL test for partition keys (which is to avoid its
			 * useless repetition).  Add the same now.
			 */
			other_parts_constr =
				makeBoolExpr(AND_EXPR,
							 lappend(get_range_nulltest(key),
									 list_length(or_expr_args) > 1
									 ? makeBoolExpr(OR_EXPR, or_expr_args,
													-1)
									 : linitial(or_expr_args)),
							 -1);

			/*
			 * Finally, the default partition contains everything *NOT*
			 * contained in the non-default partitions.
			 */
			result = list_make1(makeBoolExpr(NOT_EXPR,
											 list_make1(other_parts_constr), -1));
		}

		return result;
	}

	/*
	 * If it is the recursive call for default, we skip the get_range_nulltest
	 * to avoid accumulating the NullTest on the same keys for each partition.
	 */
	if (!for_default)
		result = get_range_nulltest(key);

	/*
	 * Iterate over the key columns and check if the corresponding lower and
	 * upper datums are equal using the btree equality operator for the
	 * column's type.  If equal, we emit single keyCol = common_value
	 * expression.  Starting from the first column for which the corresponding
	 * lower and upper bound datums are not equal, we generate OR expressions
	 * as shown in the function's header comment.
	 */
	i = 0;
	partexprs_item = list_head(key->partexprs);
	partexprs_item_saved = partexprs_item;	/* placate compiler */
	forboth(cell1, spec->lowerdatums, cell2, spec->upperdatums)
	{
		EState	   *estate;
		MemoryContext oldcxt;
		Expr	   *test_expr;
		ExprState  *test_exprstate;
		Datum		test_result;
		bool		isNull;

		ldatum = lfirst_node(PartitionRangeDatum, cell1);
		udatum = lfirst_node(PartitionRangeDatum, cell2);

		/*
		 * Since get_range_key_properties() modifies partexprs_item, and we
		 * might need to start over from the previous expression in the later
		 * part of this function, save away the current value.
		 */
		partexprs_item_saved = partexprs_item;

		get_range_key_properties(key, i, ldatum, udatum,
								 &partexprs_item,
								 &keyCol,
								 &lower_val, &upper_val);

		/*
		 * If either value is NULL, the corresponding partition bound is
		 * either MINVALUE or MAXVALUE, and we treat them as unequal, because
		 * even if they're the same, there is no common value to equate the
		 * key column with.
		 */
		if (!lower_val || !upper_val)
			break;

		/* Create the test expression */
		estate = CreateExecutorState();
		oldcxt = MemoryContextSwitchTo(estate->es_query_cxt);
		test_expr = make_partition_op_expr(key, i, BTEqualStrategyNumber,
										   (Expr *) lower_val,
										   (Expr *) upper_val);
		fix_opfuncids((Node *) test_expr);
		test_exprstate = ExecInitExpr(test_expr, NULL);
		test_result = ExecEvalExprSwitchContext(test_exprstate,
												GetPerTupleExprContext(estate),
												&isNull);
		MemoryContextSwitchTo(oldcxt);
		FreeExecutorState(estate);

		/* If not equal, go generate the OR expressions */
		if (!DatumGetBool(test_result))
			break;

		/*
		 * The bounds for the last key column can't be equal, because such a
		 * range partition would never be allowed to be defined (it would have
		 * an empty range otherwise).
		 */
		if (i == key->partnatts - 1)
			elog(ERROR, "invalid range bound specification");

		/* Equal, so generate keyCol = lower_val expression */
		result = lappend(result,
						 make_partition_op_expr(key, i, BTEqualStrategyNumber,
												keyCol, (Expr *) lower_val));

		i++;
	}

	/* First pair of lower_val and upper_val that are not equal. */
	lower_or_start_datum = cell1;
	upper_or_start_datum = cell2;

	/* OR will have as many arms as there are key columns left. */
	num_or_arms = key->partnatts - i;
	current_or_arm = 0;
	lower_or_arms = upper_or_arms = NIL;
	need_next_lower_arm = need_next_upper_arm = true;
	while (current_or_arm < num_or_arms)
	{
		List	   *lower_or_arm_args = NIL,
				   *upper_or_arm_args = NIL;

		/* Restart scan of columns from the i'th one */
		j = i;
		partexprs_item = partexprs_item_saved;

		for_both_cell(cell1, spec->lowerdatums, lower_or_start_datum,
					  cell2, spec->upperdatums, upper_or_start_datum)
		{
			PartitionRangeDatum *ldatum_next = NULL,
					   *udatum_next = NULL;

			ldatum = lfirst_node(PartitionRangeDatum, cell1);
			if (lnext(spec->lowerdatums, cell1))
				ldatum_next = castNode(PartitionRangeDatum,
									   lfirst(lnext(spec->lowerdatums, cell1)));
			udatum = lfirst_node(PartitionRangeDatum, cell2);
			if (lnext(spec->upperdatums, cell2))
				udatum_next = castNode(PartitionRangeDatum,
									   lfirst(lnext(spec->upperdatums, cell2)));
			get_range_key_properties(key, j, ldatum, udatum,
									 &partexprs_item,
									 &keyCol,
									 &lower_val, &upper_val);

			if (need_next_lower_arm && lower_val)
			{
				uint16		strategy;

				/*
				 * For the non-last columns of this arm, use the EQ operator.
				 * For the last column of this arm, use GT, unless this is the
				 * last column of the whole bound check, or the next bound
				 * datum is MINVALUE, in which case use GE.
				 */
				if (j - i < current_or_arm)
					strategy = BTEqualStrategyNumber;
				else if (j == key->partnatts - 1 ||
						 (ldatum_next &&
						  ldatum_next->kind == PARTITION_RANGE_DATUM_MINVALUE))
					strategy = BTGreaterEqualStrategyNumber;
				else
					strategy = BTGreaterStrategyNumber;

				lower_or_arm_args = lappend(lower_or_arm_args,
											make_partition_op_expr(key, j,
																   strategy,
																   keyCol,
																   (Expr *) lower_val));
			}

			if (need_next_upper_arm && upper_val)
			{
				uint16		strategy;

				/*
				 * For the non-last columns of this arm, use the EQ operator.
				 * For the last column of this arm, use LT, unless the next
				 * bound datum is MAXVALUE, in which case use LE.
				 */
				if (j - i < current_or_arm)
					strategy = BTEqualStrategyNumber;
				else if (udatum_next &&
						 udatum_next->kind == PARTITION_RANGE_DATUM_MAXVALUE)
					strategy = BTLessEqualStrategyNumber;
				else
					strategy = BTLessStrategyNumber;

				upper_or_arm_args = lappend(upper_or_arm_args,
											make_partition_op_expr(key, j,
																   strategy,
																   keyCol,
																   (Expr *) upper_val));
			}

			/*
			 * Did we generate enough of OR's arguments?  First arm considers
			 * the first of the remaining columns, second arm considers first
			 * two of the remaining columns, and so on.
			 */
			++j;
			if (j - i > current_or_arm)
			{
				/*
				 * We must not emit any more arms if the new column that will
				 * be considered is unbounded, or this one was.
				 */
				if (!lower_val || !ldatum_next ||
					ldatum_next->kind != PARTITION_RANGE_DATUM_VALUE)
					need_next_lower_arm = false;
				if (!upper_val || !udatum_next ||
					udatum_next->kind != PARTITION_RANGE_DATUM_VALUE)
					need_next_upper_arm = false;
				break;
			}
		}

		if (lower_or_arm_args != NIL)
			lower_or_arms = lappend(lower_or_arms,
									list_length(lower_or_arm_args) > 1
									? makeBoolExpr(AND_EXPR, lower_or_arm_args, -1)
									: linitial(lower_or_arm_args));

		if (upper_or_arm_args != NIL)
			upper_or_arms = lappend(upper_or_arms,
									list_length(upper_or_arm_args) > 1
									? makeBoolExpr(AND_EXPR, upper_or_arm_args, -1)
									: linitial(upper_or_arm_args));

		/* If no work to do in the next iteration, break away. */
		if (!need_next_lower_arm && !need_next_upper_arm)
			break;

		++current_or_arm;
	}

	/*
	 * Generate the OR expressions for each of lower and upper bounds (if
	 * required), and append to the list of implicitly ANDed list of
	 * expressions.
	 */
	if (lower_or_arms != NIL)
		result = lappend(result,
						 list_length(lower_or_arms) > 1
						 ? makeBoolExpr(OR_EXPR, lower_or_arms, -1)
						 : linitial(lower_or_arms));
	if (upper_or_arms != NIL)
		result = lappend(result,
						 list_length(upper_or_arms) > 1
						 ? makeBoolExpr(OR_EXPR, upper_or_arms, -1)
						 : linitial(upper_or_arms));

	/*
	 * As noted above, for non-default, we return list with constant TRUE. If
	 * the result is NIL during the recursive call for default, it implies
	 * this is the only other partition which can hold every value of the key
	 * except NULL. Hence we return the NullTest result skipped earlier.
	 */
	if (result == NIL)
		result = for_default
			? get_range_nulltest(key)
			: list_make1(makeBoolConst(true, false));

	return result;
}

/*
 * get_range_key_properties
 *		Returns range partition key information for a given column
 *
 * This is a subroutine for get_qual_for_range, and its API is pretty
 * specialized to that caller.
 *
 * Constructs an Expr for the key column (returned in *keyCol) and Consts
 * for the lower and upper range limits (returned in *lower_val and
 * *upper_val).  For MINVALUE/MAXVALUE limits, NULL is returned instead of
 * a Const.  All of these structures are freshly palloc'd.
 *
 * *partexprs_item points to the cell containing the next expression in
 * the key->partexprs list, or NULL.  It may be advanced upon return.
 */
static void
get_range_key_properties(PartitionKey key, int keynum,
						 PartitionRangeDatum *ldatum,
						 PartitionRangeDatum *udatum,
						 ListCell **partexprs_item,
						 Expr **keyCol,
						 Const **lower_val, Const **upper_val)
{
	/* Get partition key expression for this column */
	if (key->partattrs[keynum] != 0)
	{
		*keyCol = (Expr *) makeVar(1,
								   key->partattrs[keynum],
								   key->parttypid[keynum],
								   key->parttypmod[keynum],
								   key->parttypcoll[keynum],
								   0);
	}
	else
	{
		if (*partexprs_item == NULL)
			elog(ERROR, "wrong number of partition key expressions");
		*keyCol = copyObject(lfirst(*partexprs_item));
		*partexprs_item = lnext(key->partexprs, *partexprs_item);
	}

	/* Get appropriate Const nodes for the bounds */
	if (ldatum->kind == PARTITION_RANGE_DATUM_VALUE)
		*lower_val = castNode(Const, copyObject(ldatum->value));
	else
		*lower_val = NULL;

	if (udatum->kind == PARTITION_RANGE_DATUM_VALUE)
		*upper_val = castNode(Const, copyObject(udatum->value));
	else
		*upper_val = NULL;
}

/*
 * get_range_nulltest
 *
 * A non-default range partition table does not currently allow partition
 * keys to be null, so emit an IS NOT NULL expression for each key column.
 */
static List *
get_range_nulltest(PartitionKey key)
{
	List	   *result = NIL;
	NullTest   *nulltest;
	ListCell   *partexprs_item;
	int			i;

	partexprs_item = list_head(key->partexprs);
	for (i = 0; i < key->partnatts; i++)
	{
		Expr	   *keyCol;

		if (key->partattrs[i] != 0)
		{
			keyCol = (Expr *) makeVar(1,
									  key->partattrs[i],
									  key->parttypid[i],
									  key->parttypmod[i],
									  key->parttypcoll[i],
									  0);
		}
		else
		{
			if (partexprs_item == NULL)
				elog(ERROR, "wrong number of partition key expressions");
			keyCol = copyObject(lfirst(partexprs_item));
			partexprs_item = lnext(key->partexprs, partexprs_item);
		}

		nulltest = makeNode(NullTest);
		nulltest->arg = keyCol;
		nulltest->nulltesttype = IS_NOT_NULL;
		nulltest->argisrow = false;
		nulltest->location = -1;
		result = lappend(result, nulltest);
	}

	return result;
}

/*
 * compute_partition_hash_value
 *
 * Compute the hash value for given partition key values.
 */
uint64
compute_partition_hash_value(int partnatts, FmgrInfo *partsupfunc, Oid *partcollation,
							 Datum *values, bool *isnull)
{
	int			i;
	uint64		rowHash = 0;
	Datum		seed = UInt64GetDatum(HASH_PARTITION_SEED);

	for (i = 0; i < partnatts; i++)
	{
		/* Nulls are just ignored */
		if (!isnull[i])
		{
			Datum		hash;

			Assert(OidIsValid(partsupfunc[i].fn_oid));

			/*
			 * Compute hash for each datum value by calling respective
			 * datatype-specific hash functions of each partition key
			 * attribute.
			 */
			hash = FunctionCall2Coll(&partsupfunc[i], partcollation[i],
									 values[i], seed);

			/* Form a single 64-bit hash value */
			rowHash = hash_combine64(rowHash, DatumGetUInt64(hash));
		}
	}

	return rowHash;
}

/*
 * satisfies_hash_partition
 *
 * This is an SQL-callable function for use in hash partition constraints.
 * The first three arguments are the parent table OID, modulus, and remainder.
 * The remaining arguments are the value of the partitioning columns (or
 * expressions); these are hashed and the results are combined into a single
 * hash value by calling hash_combine64.
 *
 * Returns true if remainder produced when this computed single hash value is
 * divided by the given modulus is equal to given remainder, otherwise false.
 * NB: it's important that this never return null, as the constraint machinery
 * would consider that to be a "pass".
 *
 * See get_qual_for_hash() for usage.
 */
Datum
satisfies_hash_partition(PG_FUNCTION_ARGS)
{
	typedef struct ColumnsHashData
	{
		Oid			relid;
		int			nkeys;
		Oid			variadic_type;
		int16		variadic_typlen;
		bool		variadic_typbyval;
		char		variadic_typalign;
		Oid			partcollid[PARTITION_MAX_KEYS];
		FmgrInfo	partsupfunc[FLEXIBLE_ARRAY_MEMBER];
	} ColumnsHashData;
	Oid			parentId;
	int			modulus;
	int			remainder;
	Datum		seed = UInt64GetDatum(HASH_PARTITION_SEED);
	ColumnsHashData *my_extra;
	uint64		rowHash = 0;

	/* Return false if the parent OID, modulus, or remainder is NULL. */
	if (PG_ARGISNULL(0) || PG_ARGISNULL(1) || PG_ARGISNULL(2))
		PG_RETURN_BOOL(false);
	parentId = PG_GETARG_OID(0);
	modulus = PG_GETARG_INT32(1);
	remainder = PG_GETARG_INT32(2);

	/* Sanity check modulus and remainder. */
	if (modulus <= 0)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("modulus for hash partition must be an integer value greater than zero")));
	if (remainder < 0)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("remainder for hash partition must be an integer value greater than or equal to zero")));
	if (remainder >= modulus)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("remainder for hash partition must be less than modulus")));

	/*
	 * Cache hash function information.
	 */
	my_extra = (ColumnsHashData *) fcinfo->flinfo->fn_extra;
	if (my_extra == NULL || my_extra->relid != parentId)
	{
		Relation	parent;
		PartitionKey key;
		int			j;

		/* Open parent relation and fetch partition key info */
		parent = relation_open(parentId, AccessShareLock);
		key = RelationGetPartitionKey(parent);

		/* Reject parent table that is not hash-partitioned. */
		if (key == NULL || key->strategy != PARTITION_STRATEGY_HASH)
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
					 errmsg("\"%s\" is not a hash partitioned table",
							get_rel_name(parentId))));

		if (!get_fn_expr_variadic(fcinfo->flinfo))
		{
			int			nargs = PG_NARGS() - 3;

			/* complain if wrong number of column values */
			if (key->partnatts != nargs)
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
						 errmsg("number of partitioning columns (%d) does not match number of partition keys provided (%d)",
								key->partnatts, nargs)));

			/* allocate space for our cache */
			fcinfo->flinfo->fn_extra =
				MemoryContextAllocZero(fcinfo->flinfo->fn_mcxt,
									   offsetof(ColumnsHashData, partsupfunc) +
									   sizeof(FmgrInfo) * nargs);
			my_extra = (ColumnsHashData *) fcinfo->flinfo->fn_extra;
			my_extra->relid = parentId;
			my_extra->nkeys = key->partnatts;
			memcpy(my_extra->partcollid, key->partcollation,
				   key->partnatts * sizeof(Oid));

			/* check argument types and save fmgr_infos */
			for (j = 0; j < key->partnatts; ++j)
			{
				Oid			argtype = get_fn_expr_argtype(fcinfo->flinfo, j + 3);

				if (argtype != key->parttypid[j] && !IsBinaryCoercible(argtype, key->parttypid[j]))
					ereport(ERROR,
							(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
							 errmsg("column %d of the partition key has type %s, but supplied value is of type %s",
									j + 1, format_type_be(key->parttypid[j]), format_type_be(argtype))));

				fmgr_info_copy(&my_extra->partsupfunc[j],
							   &key->partsupfunc[j],
							   fcinfo->flinfo->fn_mcxt);
			}
		}
		else
		{
			ArrayType  *variadic_array = PG_GETARG_ARRAYTYPE_P(3);

			/* allocate space for our cache -- just one FmgrInfo in this case */
			fcinfo->flinfo->fn_extra =
				MemoryContextAllocZero(fcinfo->flinfo->fn_mcxt,
									   offsetof(ColumnsHashData, partsupfunc) +
									   sizeof(FmgrInfo));
			my_extra = (ColumnsHashData *) fcinfo->flinfo->fn_extra;
			my_extra->relid = parentId;
			my_extra->nkeys = key->partnatts;
			my_extra->variadic_type = ARR_ELEMTYPE(variadic_array);
			get_typlenbyvalalign(my_extra->variadic_type,
								 &my_extra->variadic_typlen,
								 &my_extra->variadic_typbyval,
								 &my_extra->variadic_typalign);
			my_extra->partcollid[0] = key->partcollation[0];

			/* check argument types */
			for (j = 0; j < key->partnatts; ++j)
				if (key->parttypid[j] != my_extra->variadic_type)
					ereport(ERROR,
							(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
							 errmsg("column %d of the partition key has type \"%s\", but supplied value is of type \"%s\"",
									j + 1,
									format_type_be(key->parttypid[j]),
									format_type_be(my_extra->variadic_type))));

			fmgr_info_copy(&my_extra->partsupfunc[0],
						   &key->partsupfunc[0],
						   fcinfo->flinfo->fn_mcxt);
		}

		/* Hold lock until commit */
		relation_close(parent, NoLock);
	}

	if (!OidIsValid(my_extra->variadic_type))
	{
		int			nkeys = my_extra->nkeys;
		int			i;

		/*
		 * For a non-variadic call, neither the number of arguments nor their
		 * types can change across calls, so avoid the expense of rechecking
		 * here.
		 */

		for (i = 0; i < nkeys; i++)
		{
			Datum		hash;

			/* keys start from fourth argument of function. */
			int			argno = i + 3;

			if (PG_ARGISNULL(argno))
				continue;

			hash = FunctionCall2Coll(&my_extra->partsupfunc[i],
									 my_extra->partcollid[i],
									 PG_GETARG_DATUM(argno),
									 seed);

			/* Form a single 64-bit hash value */
			rowHash = hash_combine64(rowHash, DatumGetUInt64(hash));
		}
	}
	else
	{
		ArrayType  *variadic_array = PG_GETARG_ARRAYTYPE_P(3);
		int			i;
		int			nelems;
		Datum	   *datum;
		bool	   *isnull;

		deconstruct_array(variadic_array,
						  my_extra->variadic_type,
						  my_extra->variadic_typlen,
						  my_extra->variadic_typbyval,
						  my_extra->variadic_typalign,
						  &datum, &isnull, &nelems);

		/* complain if wrong number of column values */
		if (nelems != my_extra->nkeys)
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
					 errmsg("number of partitioning columns (%d) does not match number of partition keys provided (%d)",
							my_extra->nkeys, nelems)));

		for (i = 0; i < nelems; i++)
		{
			Datum		hash;

			if (isnull[i])
				continue;

			hash = FunctionCall2Coll(&my_extra->partsupfunc[0],
									 my_extra->partcollid[0],
									 datum[i],
									 seed);

			/* Form a single 64-bit hash value */
			rowHash = hash_combine64(rowHash, DatumGetUInt64(hash));
		}
	}

	PG_RETURN_BOOL(rowHash % modulus == remainder);
}