paimon-datafusion 0.3.0

Apache Paimon DataFusion Integration
Documentation
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

//! E2E integration tests for primary-key tables via DataFusion SQL.
//!
//! Covers: basic write+read, dedup within/across commits, partitioned PK tables,
//! multi-bucket, column projection, FirstRow merge engine, sequence.field,
//! INSERT OVERWRITE, filter pushdown, cross-split merge correctness,
//! aggregation merge engine, and error cases.
//!
//! Dynamic bucket and cross-partition tests are in separate files:
//! - `dynamic_bucket_tables.rs`
//! - `cross_partition_tables.rs`

mod common;

use common::{
    collect_id_name, collect_id_value, collect_int_int_str, create_sql_context, create_test_env,
    row_count, setup_sql_context, string_value,
};
use datafusion::arrow::array::{Array, Int32Array, Int64Array, Int8Array, RecordBatch};
use datafusion::arrow::datatypes::{
    DataType as ArrowDataType, Field as ArrowField, Schema as ArrowSchema,
};
use paimon::catalog::Identifier;
use paimon::Catalog;
use paimon_datafusion::PaimonTableProvider;
use std::collections::HashMap;
use std::sync::Arc;

// ======================= Basic PK Write + Read =======================

/// Basic: CREATE TABLE with PK, INSERT, SELECT — verifies round-trip.
#[tokio::test]
async fn test_pk_basic_write_read() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t1 (
                id INT NOT NULL, name STRING,
                PRIMARY KEY (id)
            ) WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    sql_context
        .sql("INSERT INTO paimon.test_db.t1 VALUES (1, 'alice'), (2, 'bob'), (3, 'carol')")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let rows = collect_id_name(
        &sql_context,
        "SELECT id, name FROM paimon.test_db.t1 ORDER BY id",
    )
    .await;

    assert_eq!(
        rows,
        vec![
            (1, "alice".to_string()),
            (2, "bob".to_string()),
            (3, "carol".to_string()),
        ]
    );
}

/// Partial-update merge engine: keep latest non-null value for each field.
#[tokio::test]
async fn test_pk_partial_update_fixed_bucket_e2e() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_partial_update (
                id INT NOT NULL, v_int INT, v_str STRING,
                PRIMARY KEY (id)
            ) WITH ('bucket' = '1', 'merge-engine' = 'partial-update')",
        )
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_partial_update VALUES
             (1, 10, 'old-1'),
             (2, 20, 'old-2')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_partial_update VALUES
             (1, CAST(NULL AS INT), 'new-1'),
             (2, 200, CAST(NULL AS STRING)),
             (3, 30, CAST(NULL AS STRING))",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_partial_update VALUES
             (1, 111, CAST(NULL AS STRING))",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT id, v_int, v_str FROM paimon.test_db.t_partial_update ORDER BY id")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let mut rows = Vec::new();
    for batch in &batches {
        let ids = batch
            .column_by_name("id")
            .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
            .unwrap();
        let ints = batch
            .column_by_name("v_int")
            .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
            .unwrap();
        let strs = batch.column_by_name("v_str").unwrap();
        for i in 0..batch.num_rows() {
            rows.push((
                ids.value(i),
                if ints.is_null(i) {
                    None
                } else {
                    Some(ints.value(i))
                },
                if strs.is_null(i) {
                    None
                } else {
                    Some(string_value(strs.as_ref(), i).to_string())
                },
            ));
        }
    }

    assert_eq!(
        rows,
        vec![
            (1, Some(111), Some("new-1".to_string())),
            (2, Some(200), Some("old-2".to_string())),
            (3, Some(30), None),
        ]
    );
}

#[tokio::test]
async fn test_pk_partial_update_sequence_group_aggregation_read_e2e() {
    let (_tmp, catalog) = create_test_env();
    let sql_context = create_sql_context(catalog.clone()).await;
    sql_context
        .sql("CREATE SCHEMA paimon.test_db")
        .await
        .unwrap();

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_partial_update_aggregation (
                id INT NOT NULL,
                version INT,
                amount INT,
                tag STRING,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'merge-engine' = 'partial-update'
            )",
        )
        .await
        .unwrap();

    for values in [
        "(1, 10, 10, 'b'), (2, 5, 3, 'x')",
        "(1, 9, 20, 'a'), (2, 4, 4, 'w')",
        "(1, 11, 5, 'c')",
    ] {
        sql_context
            .sql(&format!(
                "INSERT INTO paimon.test_db.t_partial_update_aggregation VALUES {values}"
            ))
            .await
            .unwrap()
            .collect()
            .await
            .unwrap();
    }

    let table = catalog
        .get_table(&Identifier::new("test_db", "t_partial_update_aggregation"))
        .await
        .unwrap()
        .copy_with_options(HashMap::from([
            (
                "fields.version.sequence-group".to_string(),
                "amount,tag".to_string(),
            ),
            (
                "fields.amount.aggregate-function".to_string(),
                "sum".to_string(),
            ),
            (
                "fields.tag.aggregate-function".to_string(),
                "listagg".to_string(),
            ),
        ]));
    let provider = PaimonTableProvider::try_new(table).unwrap();
    sql_context
        .register_temp_table(
            "paimon.test_db.t_partial_update_aggregation",
            Arc::new(provider),
        )
        .unwrap();

    let batches = sql_context
        .sql(
            "SELECT id
             FROM paimon.test_db.t_partial_update_aggregation
             WHERE amount = 7 AND tag = 'w,x'",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::<usize>(), 1);
    let batch = &batches[0];
    assert_eq!(
        batch
            .column_by_name("id")
            .unwrap()
            .as_any()
            .downcast_ref::<Int32Array>()
            .unwrap()
            .value(0),
        2
    );
    assert_eq!(
        batch
            .schema()
            .fields()
            .iter()
            .map(|field| field.name().as_str())
            .collect::<Vec<_>>(),
        vec!["id"]
    );
}

#[tokio::test]
async fn test_pk_partial_update_ignore_delete_alias_e2e() {
    let (_tmp, catalog) = create_test_env();
    let sql_context = create_sql_context(catalog.clone()).await;
    sql_context
        .sql("CREATE SCHEMA paimon.test_db")
        .await
        .unwrap();
    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_partial_update_ignore_delete (
                id INT NOT NULL, value INT,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'merge-engine' = 'partial-update',
                'partial-update.ignore-delete' = 'true'
            )",
        )
        .await
        .unwrap();

    let table = catalog
        .get_table(&Identifier::new(
            "test_db",
            "t_partial_update_ignore_delete",
        ))
        .await
        .unwrap();
    let batch = RecordBatch::try_new(
        Arc::new(ArrowSchema::new(vec![
            ArrowField::new("id", ArrowDataType::Int32, false),
            ArrowField::new("value", ArrowDataType::Int32, true),
            ArrowField::new("_VALUE_KIND", ArrowDataType::Int8, false),
        ])),
        vec![
            Arc::new(Int32Array::from(vec![1, 1, 2, 1])),
            Arc::new(Int32Array::from(vec![
                Some(10),
                Some(999),
                Some(200),
                Some(20),
            ])),
            Arc::new(Int8Array::from(vec![0, 3, 1, 2])),
        ],
    )
    .unwrap();
    let write_builder = table.new_write_builder();
    let mut write = write_builder.new_write().unwrap();
    write.write_arrow_batch(&batch).await.unwrap();
    let messages = write.prepare_commit().await.unwrap();
    write_builder.new_commit().commit(messages).await.unwrap();

    assert_eq!(
        collect_id_value(
            &sql_context,
            "SELECT id, value
             FROM paimon.test_db.t_partial_update_ignore_delete
             ORDER BY id",
        )
        .await,
        vec![(1, 20)]
    );
}

/// Partial updates of one key within a single INSERT are merged at flush
/// (mirrors Java MergeTreeWriter#flushWriteBuffer): the flushed file holds
/// one row per key, so SELECT and COUNT(*) agree.
#[tokio::test]
async fn test_pk_partial_update_merges_within_single_commit() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_pu_flush_merge (
                id INT NOT NULL, v_int INT, v_str STRING,
                PRIMARY KEY (id)
            ) WITH ('bucket' = '1', 'merge-engine' = 'partial-update')",
        )
        .await
        .unwrap();

    // Three partial updates of key 1 plus key 2 in ONE commit: the writer
    // must merge key 1 down to a single physical row.
    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_pu_flush_merge VALUES
             (1, 10, CAST(NULL AS STRING)),
             (1, CAST(NULL AS INT), 'hello'),
             (1, 100, CAST(NULL AS STRING)),
             (2, 200, 'world')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Field-wise merge result: latest non-null per column.
    let batches = sql_context
        .sql("SELECT id, v_int, v_str FROM paimon.test_db.t_pu_flush_merge ORDER BY id")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();
    assert_eq!(
        collect_int_int_str(&batches),
        vec![(1, 100, "hello".to_string()), (2, 200, "world".to_string())]
    );

    // COUNT(*) must agree with SELECT: physical rows now equal merged rows.
    let batches = sql_context
        .sql("SELECT COUNT(*) FROM paimon.test_db.t_pu_flush_merge")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();
    let count = batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<datafusion::arrow::array::Int64Array>()
        .unwrap()
        .value(0);
    assert_eq!(count, 2, "COUNT(*) must count merged rows");
}

// ======================= Dedup Within Single Commit =======================

/// Duplicate keys in a single INSERT — last value wins (Deduplicate engine).
#[tokio::test]
async fn test_pk_dedup_within_single_commit() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_dedup (
                id INT NOT NULL, value INT,
                PRIMARY KEY (id)
            ) WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    sql_context
        .sql("INSERT INTO paimon.test_db.t_dedup VALUES (1, 10), (2, 20), (1, 100), (2, 200)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let rows = collect_id_value(
        &sql_context,
        "SELECT id, value FROM paimon.test_db.t_dedup ORDER BY id",
    )
    .await;

    // Last occurrence wins for deduplicate merge engine
    assert_eq!(rows, vec![(1, 100), (2, 200)]);
}

// ======================= Dedup Across Commits =======================

/// Two commits with overlapping keys — second commit's values win.
#[tokio::test]
async fn test_pk_dedup_across_commits() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_cross (
                id INT NOT NULL, name STRING,
                PRIMARY KEY (id)
            ) WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    // First commit
    sql_context
        .sql("INSERT INTO paimon.test_db.t_cross VALUES (1, 'alice'), (2, 'bob'), (3, 'carol')")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Second commit: update id=1,3, add id=4
    sql_context
        .sql("INSERT INTO paimon.test_db.t_cross VALUES (1, 'alice-v2'), (3, 'carol-v2'), (4, 'dave')")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let rows = collect_id_name(
        &sql_context,
        "SELECT id, name FROM paimon.test_db.t_cross ORDER BY id",
    )
    .await;

    assert_eq!(
        rows,
        vec![
            (1, "alice-v2".to_string()),
            (2, "bob".to_string()),
            (3, "carol-v2".to_string()),
            (4, "dave".to_string()),
        ]
    );
}

// ======================= Three Commits =======================

/// Three successive commits — verifies sequence number tracking across commits.
#[tokio::test]
async fn test_pk_three_commits() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_three (
                id INT NOT NULL, value INT,
                PRIMARY KEY (id)
            ) WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    sql_context
        .sql("INSERT INTO paimon.test_db.t_three VALUES (1, 10), (2, 20)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    sql_context
        .sql("INSERT INTO paimon.test_db.t_three VALUES (2, 200), (3, 30)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    sql_context
        .sql("INSERT INTO paimon.test_db.t_three VALUES (1, 100), (3, 300), (4, 40)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let rows = collect_id_value(
        &sql_context,
        "SELECT id, value FROM paimon.test_db.t_three ORDER BY id",
    )
    .await;

    assert_eq!(rows, vec![(1, 100), (2, 200), (3, 300), (4, 40)]);
}

// ======================= Partitioned PK Table =======================

/// Partitioned PK table: dedup happens per-partition independently.
#[tokio::test]
async fn test_pk_partitioned_write_read() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_part (
                dt STRING, id INT NOT NULL, name STRING,
                PRIMARY KEY (dt, id)
            ) PARTITIONED BY (dt)
            WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_part VALUES \
             ('2024-01-01', 1, 'alice'), ('2024-01-01', 2, 'bob'), \
             ('2024-01-02', 1, 'carol'), ('2024-01-02', 2, 'dave')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let rows = collect_id_name(
        &sql_context,
        "SELECT id, name FROM paimon.test_db.t_part ORDER BY id, name",
    )
    .await;

    assert_eq!(
        rows,
        vec![
            (1, "alice".to_string()),
            (1, "carol".to_string()),
            (2, "bob".to_string()),
            (2, "dave".to_string()),
        ]
    );
}

/// Partitioned PK table: dedup across commits within same partition.
#[tokio::test]
async fn test_pk_partitioned_dedup_across_commits() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_part_dedup (
                dt STRING, id INT NOT NULL, name STRING,
                PRIMARY KEY (dt, id)
            ) PARTITIONED BY (dt)
            WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_part_dedup VALUES \
             ('2024-01-01', 1, 'alice'), ('2024-01-01', 2, 'bob'), \
             ('2024-01-02', 1, 'carol')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Update within partition 2024-01-01
    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_part_dedup VALUES \
             ('2024-01-01', 1, 'alice-v2'), ('2024-01-02', 2, 'dave')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT dt, id, name FROM paimon.test_db.t_part_dedup ORDER BY dt, id")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let mut rows = Vec::new();
    for batch in &batches {
        let dts = batch.column_by_name("dt").unwrap();
        let ids = batch
            .column_by_name("id")
            .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
            .unwrap();
        let names = batch.column_by_name("name").unwrap();
        for i in 0..batch.num_rows() {
            rows.push((
                string_value(dts.as_ref(), i).to_string(),
                ids.value(i),
                string_value(names.as_ref(), i).to_string(),
            ));
        }
    }

    assert_eq!(
        rows,
        vec![
            ("2024-01-01".to_string(), 1, "alice-v2".to_string()),
            ("2024-01-01".to_string(), 2, "bob".to_string()),
            ("2024-01-02".to_string(), 1, "carol".to_string()),
            ("2024-01-02".to_string(), 2, "dave".to_string()),
        ]
    );
}

/// Partition filter on PK table — only matching partition returned.
#[tokio::test]
async fn test_pk_partitioned_filter() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_part_filter (
                dt STRING, id INT NOT NULL, name STRING,
                PRIMARY KEY (dt, id)
            ) PARTITIONED BY (dt)
            WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_part_filter VALUES \
             ('2024-01-01', 1, 'alice'), ('2024-01-01', 2, 'bob'), \
             ('2024-01-02', 3, 'carol')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let rows = collect_id_name(
        &sql_context,
        "SELECT id, name FROM paimon.test_db.t_part_filter WHERE dt = '2024-01-01' ORDER BY id",
    )
    .await;

    assert_eq!(rows, vec![(1, "alice".to_string()), (2, "bob".to_string())]);
}

// ======================= Multi-Bucket PK Table =======================

/// Multiple buckets: rows are distributed by PK hash, dedup still works.
#[tokio::test]
async fn test_pk_multi_bucket() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_mbucket (
                id INT NOT NULL, value INT,
                PRIMARY KEY (id)
            ) WITH ('bucket' = '4')",
        )
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_mbucket VALUES \
             (1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60), (7, 70), (8, 80)",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Update some keys
    sql_context
        .sql("INSERT INTO paimon.test_db.t_mbucket VALUES (2, 200), (5, 500), (8, 800)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let rows = collect_id_value(
        &sql_context,
        "SELECT id, value FROM paimon.test_db.t_mbucket ORDER BY id",
    )
    .await;

    assert_eq!(
        rows,
        vec![
            (1, 10),
            (2, 200),
            (3, 30),
            (4, 40),
            (5, 500),
            (6, 60),
            (7, 70),
            (8, 800),
        ]
    );
}

// ======================= Column Projection =======================

/// SELECT only a subset of columns from a PK table.
#[tokio::test]
async fn test_pk_column_projection() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_proj (
                id INT NOT NULL, name STRING, value INT,
                PRIMARY KEY (id)
            ) WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    sql_context
        .sql("INSERT INTO paimon.test_db.t_proj VALUES (1, 'alice', 10), (2, 'bob', 20)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Update id=1
    sql_context
        .sql("INSERT INTO paimon.test_db.t_proj VALUES (1, 'alice-v2', 100)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Project only name
    let batches = sql_context
        .sql("SELECT name FROM paimon.test_db.t_proj ORDER BY name")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let mut names = Vec::new();
    for batch in &batches {
        let arr = batch.column(0);
        for i in 0..batch.num_rows() {
            names.push(string_value(arr.as_ref(), i).to_string());
        }
    }
    names.sort();
    assert_eq!(names, vec!["alice-v2", "bob"]);

    // Project only value
    let rows = collect_id_value(
        &sql_context,
        "SELECT id, value FROM paimon.test_db.t_proj ORDER BY id",
    )
    .await;
    assert_eq!(rows, vec![(1, 100), (2, 20)]);
}

// ======================= Sequence Field =======================

/// sequence.field: dedup uses the specified field instead of system sequence number.
#[tokio::test]
async fn test_pk_sequence_field() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_seqf (
                id INT NOT NULL, version INT, name STRING,
                PRIMARY KEY (id)
            ) WITH ('bucket' = '1', 'sequence.field' = 'version')",
        )
        .await
        .unwrap();

    // First commit: version=2 for id=1
    sql_context
        .sql("INSERT INTO paimon.test_db.t_seqf VALUES (1, 2, 'alice-v2'), (2, 1, 'bob-v1')")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Second commit: version=1 for id=1 (older), version=2 for id=2 (newer)
    sql_context
        .sql("INSERT INTO paimon.test_db.t_seqf VALUES (1, 1, 'alice-v1'), (2, 2, 'bob-v2')")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let rows = collect_id_name(
        &sql_context,
        "SELECT id, name FROM paimon.test_db.t_seqf ORDER BY id",
    )
    .await;

    assert_eq!(
        rows,
        vec![
            (1, "alice-v2".to_string()), // version=2 wins over version=1
            (2, "bob-v2".to_string()),   // version=2 wins over version=1
        ]
    );
}

// ======================= INSERT OVERWRITE =======================

/// INSERT OVERWRITE on a partitioned PK table replaces the partition.
#[tokio::test]
async fn test_pk_insert_overwrite_partitioned() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_overwrite (
                dt STRING, id INT NOT NULL, name STRING,
                PRIMARY KEY (dt, id)
            ) PARTITIONED BY (dt)
            WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_overwrite VALUES \
             ('2024-01-01', 1, 'alice'), ('2024-01-01', 2, 'bob'), \
             ('2024-01-02', 3, 'carol')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Overwrite partition 2024-01-01
    sql_context
        .sql("INSERT OVERWRITE paimon.test_db.t_overwrite VALUES ('2024-01-01', 10, 'new_alice')")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT dt, id, name FROM paimon.test_db.t_overwrite ORDER BY dt, id")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let mut rows = Vec::new();
    for batch in &batches {
        let dts = batch.column_by_name("dt").unwrap();
        let ids = batch
            .column_by_name("id")
            .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
            .unwrap();
        let names = batch.column_by_name("name").unwrap();
        for i in 0..batch.num_rows() {
            rows.push((
                string_value(dts.as_ref(), i).to_string(),
                ids.value(i),
                string_value(names.as_ref(), i).to_string(),
            ));
        }
    }

    assert_eq!(
        rows,
        vec![
            ("2024-01-01".to_string(), 10, "new_alice".to_string()),
            ("2024-01-02".to_string(), 3, "carol".to_string()),
        ]
    );
}

/// INSERT OVERWRITE with explicit PARTITION clause (Hive-style static partition).
#[tokio::test]
async fn test_pk_insert_overwrite_with_partition_clause() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_ow_part (
                dt STRING, id INT NOT NULL, name STRING,
                PRIMARY KEY (dt, id)
            ) PARTITIONED BY (dt)
            WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    // Insert data into two partitions
    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_ow_part VALUES \
             ('2024-01-01', 1, 'alice'), ('2024-01-01', 2, 'bob'), \
             ('2024-01-02', 3, 'carol')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Overwrite partition dt='2024-01-01' using Hive-style PARTITION clause.
    // The SELECT only provides non-partition columns (id, name).
    sql_context
        .sql(
            "INSERT OVERWRITE paimon.test_db.t_ow_part PARTITION (dt = '2024-01-01') \
             VALUES (10, 'new_alice'), (20, 'new_bob')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT dt, id, name FROM paimon.test_db.t_ow_part ORDER BY dt, id")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let mut rows = Vec::new();
    for batch in &batches {
        let dts = batch.column_by_name("dt").unwrap();
        let ids = batch
            .column_by_name("id")
            .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
            .unwrap();
        let names = batch.column_by_name("name").unwrap();
        for i in 0..batch.num_rows() {
            rows.push((
                string_value(dts.as_ref(), i).to_string(),
                ids.value(i),
                string_value(names.as_ref(), i).to_string(),
            ));
        }
    }

    // Partition 2024-01-01 overwritten, 2024-01-02 untouched
    assert_eq!(
        rows,
        vec![
            ("2024-01-01".to_string(), 10, "new_alice".to_string()),
            ("2024-01-01".to_string(), 20, "new_bob".to_string()),
            ("2024-01-02".to_string(), 3, "carol".to_string()),
        ]
    );
}

/// INSERT OVERWRITE with partial PARTITION clause on a multi-level partitioned table.
/// Only specifies dt, region comes from the source query (dynamic partition).
#[tokio::test]
async fn test_pk_insert_overwrite_partial_partition_clause() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_multi_part (
                dt STRING, region STRING, id INT NOT NULL, name STRING,
                PRIMARY KEY (dt, region, id)
            ) PARTITIONED BY (dt, region)
            WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    // Insert data into multiple partitions
    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_multi_part VALUES \
             ('2024-01-01', 'us', 1, 'alice'), \
             ('2024-01-01', 'eu', 2, 'bob'), \
             ('2024-01-02', 'us', 3, 'carol')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Overwrite only dt='2024-01-01', region comes from VALUES (dynamic).
    // This should overwrite all sub-partitions under dt='2024-01-01' that appear in the data.
    sql_context
        .sql(
            "INSERT OVERWRITE paimon.test_db.t_multi_part PARTITION (dt = '2024-01-01') \
             VALUES ('us', 10, 'new_alice')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT dt, region, id, name FROM paimon.test_db.t_multi_part ORDER BY dt, region, id")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let mut rows = Vec::new();
    for batch in &batches {
        let dts = batch.column_by_name("dt").unwrap();
        let regions = batch.column_by_name("region").unwrap();
        let ids = batch
            .column_by_name("id")
            .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
            .unwrap();
        let names = batch.column_by_name("name").unwrap();
        for i in 0..batch.num_rows() {
            rows.push((
                string_value(dts.as_ref(), i).to_string(),
                string_value(regions.as_ref(), i).to_string(),
                ids.value(i),
                string_value(names.as_ref(), i).to_string(),
            ));
        }
    }

    // dt='2024-01-01' fully overwritten (static partition overwrite deletes all sub-partitions).
    // dt='2024-01-01'/region='eu' (bob) is deleted because the entire dt='2024-01-01' partition is replaced.
    // dt='2024-01-02'/region='us' untouched.
    assert_eq!(
        rows,
        vec![
            (
                "2024-01-01".to_string(),
                "us".to_string(),
                10,
                "new_alice".to_string()
            ),
            (
                "2024-01-02".to_string(),
                "us".to_string(),
                3,
                "carol".to_string()
            ),
        ]
    );
}

/// INSERT OVERWRITE with PARTITION clause and empty source truncates the partition.
#[tokio::test]
async fn test_pk_insert_overwrite_partition_truncate() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_trunc (
                dt STRING, id INT NOT NULL, name STRING,
                PRIMARY KEY (dt, id)
            ) PARTITIONED BY (dt)
            WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_trunc VALUES \
             ('2024-01-01', 1, 'alice'), ('2024-01-01', 2, 'bob'), \
             ('2024-01-02', 3, 'carol')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Overwrite dt='2024-01-01' with empty source — should truncate that partition
    sql_context
        .sql(
            "INSERT OVERWRITE paimon.test_db.t_trunc PARTITION (dt = '2024-01-01') \
             SELECT id, name FROM paimon.test_db.t_trunc WHERE false",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT dt, id, name FROM paimon.test_db.t_trunc ORDER BY dt, id")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let mut rows = Vec::new();
    for batch in &batches {
        let dts = batch.column_by_name("dt").unwrap();
        let ids = batch
            .column_by_name("id")
            .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
            .unwrap();
        let names = batch.column_by_name("name").unwrap();
        for i in 0..batch.num_rows() {
            rows.push((
                string_value(dts.as_ref(), i).to_string(),
                ids.value(i),
                string_value(names.as_ref(), i).to_string(),
            ));
        }
    }

    // dt='2024-01-01' truncated, dt='2024-01-02' untouched
    assert_eq!(
        rows,
        vec![("2024-01-02".to_string(), 3, "carol".to_string()),]
    );
}

/// PARTITION clause with a non-partition column should fail.
#[tokio::test]
async fn test_pk_insert_overwrite_partition_non_partition_column_error() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_err (
                dt STRING, id INT NOT NULL, name STRING,
                PRIMARY KEY (dt, id)
            ) PARTITIONED BY (dt)
            WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    let result = sql_context
        .sql(
            "INSERT OVERWRITE paimon.test_db.t_err PARTITION (name = 'alice') \
             VALUES (1)",
        )
        .await;

    assert!(result.is_err());
    let err_msg = result.unwrap_err().to_string();
    assert!(
        err_msg.contains("not a partition column"),
        "Expected 'not a partition column' error, got: {err_msg}"
    );
}

/// All-dynamic PARTITION clause (no static values) should use dynamic partition overwrite,
/// not drop all partitions.
#[tokio::test]
async fn test_pk_insert_overwrite_dynamic_partition_preserves_other_partitions() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_dyn (
                dt STRING, id INT NOT NULL, name STRING,
                PRIMARY KEY (dt, id)
            ) PARTITIONED BY (dt)
            WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_dyn VALUES \
             ('2024-01-01', 1, 'alice'), ('2024-01-02', 2, 'bob')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Dynamic partition overwrite: PARTITION (dt) with no static value.
    // Should only overwrite partitions present in the source data.
    sql_context
        .sql(
            "INSERT OVERWRITE paimon.test_db.t_dyn PARTITION (dt) \
             VALUES ('2024-01-01', 10, 'new_alice')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT dt, id, name FROM paimon.test_db.t_dyn ORDER BY dt, id")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let mut rows = Vec::new();
    for batch in &batches {
        let dts = batch.column_by_name("dt").unwrap();
        let ids = batch
            .column_by_name("id")
            .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
            .unwrap();
        let names = batch.column_by_name("name").unwrap();
        for i in 0..batch.num_rows() {
            rows.push((
                string_value(dts.as_ref(), i).to_string(),
                ids.value(i),
                string_value(names.as_ref(), i).to_string(),
            ));
        }
    }

    // dt='2024-01-01' overwritten, dt='2024-01-02' preserved
    assert_eq!(
        rows,
        vec![
            ("2024-01-01".to_string(), 10, "new_alice".to_string()),
            ("2024-01-02".to_string(), 2, "bob".to_string()),
        ]
    );
}

/// Source query with wrong column count should fail even when the result is empty.
#[tokio::test]
async fn test_pk_insert_overwrite_empty_source_wrong_columns_error() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_empty_err (
                dt STRING, id INT NOT NULL, name STRING,
                PRIMARY KEY (dt, id)
            ) PARTITIONED BY (dt)
            WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_empty_err VALUES \
             ('2024-01-01', 1, 'alice')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Source only produces `id` but target expects `id, name` — should fail
    let result = sql_context
        .sql(
            "INSERT OVERWRITE paimon.test_db.t_empty_err PARTITION (dt = '2024-01-01') \
             SELECT id FROM paimon.test_db.t_empty_err WHERE false",
        )
        .await;

    assert!(result.is_err());
    let err_msg = result.unwrap_err().to_string();
    assert!(
        err_msg.contains("expected 2 non-partition columns"),
        "Expected column count mismatch error, got: {err_msg}"
    );
}

/// Explicit target column list after PARTITION should reorder source columns to match schema.
#[tokio::test]
async fn test_pk_insert_overwrite_with_after_columns_reorder() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_reorder (
                dt STRING, id INT NOT NULL, name STRING,
                PRIMARY KEY (dt, id)
            ) PARTITIONED BY (dt)
            WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    // Insert with columns in reversed order: (name, id) instead of schema order (id, name)
    sql_context
        .sql(
            "INSERT OVERWRITE paimon.test_db.t_reorder (name, id) PARTITION (dt = '2024-01-01') \
             VALUES ('alice', 1), ('bob', 2)",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT dt, id, name FROM paimon.test_db.t_reorder ORDER BY id")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let mut rows = Vec::new();
    for batch in &batches {
        let dts = batch.column_by_name("dt").unwrap();
        let ids = batch
            .column_by_name("id")
            .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
            .unwrap();
        let names = batch.column_by_name("name").unwrap();
        for i in 0..batch.num_rows() {
            rows.push((
                string_value(dts.as_ref(), i).to_string(),
                ids.value(i),
                string_value(names.as_ref(), i).to_string(),
            ));
        }
    }

    // Values should be correctly mapped: name='alice'/id=1, name='bob'/id=2
    assert_eq!(
        rows,
        vec![
            ("2024-01-01".to_string(), 1, "alice".to_string()),
            ("2024-01-01".to_string(), 2, "bob".to_string()),
        ]
    );
}

// ======================= Composite Primary Key =======================

/// Composite PK with multiple columns.
#[tokio::test]
async fn test_pk_composite_key() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_composite (
                region STRING NOT NULL, id INT NOT NULL, value INT,
                PRIMARY KEY (region, id)
            ) WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_composite VALUES \
             ('us', 1, 10), ('eu', 1, 20), ('us', 2, 30)",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Update (us, 1) — (eu, 1) should be untouched
    sql_context
        .sql("INSERT INTO paimon.test_db.t_composite VALUES ('us', 1, 100)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT region, id, value FROM paimon.test_db.t_composite ORDER BY region, id")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let mut rows = Vec::new();
    for batch in &batches {
        let regions = batch.column_by_name("region").unwrap();
        let ids = batch
            .column_by_name("id")
            .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
            .unwrap();
        let vals = batch
            .column_by_name("value")
            .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
            .unwrap();
        for i in 0..batch.num_rows() {
            rows.push((
                string_value(regions.as_ref(), i).to_string(),
                ids.value(i),
                vals.value(i),
            ));
        }
    }

    assert_eq!(
        rows,
        vec![
            ("eu".to_string(), 1, 20),  // untouched
            ("us".to_string(), 1, 100), // updated
            ("us".to_string(), 2, 30),  // untouched
        ]
    );
}

// ======================= Empty Table Read =======================

/// Reading an empty PK table returns zero rows.
#[tokio::test]
async fn test_pk_empty_table_read() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_empty (
                id INT NOT NULL, name STRING,
                PRIMARY KEY (id)
            ) WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    let count = row_count(&sql_context, "SELECT id, name FROM paimon.test_db.t_empty").await;
    assert_eq!(count, 0);
}

// ======================= Large Batch Dedup =======================

/// Many rows with overlapping keys in a single commit.
#[tokio::test]
async fn test_pk_large_batch_dedup() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_large (
                id INT NOT NULL, value INT,
                PRIMARY KEY (id)
            ) WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    // Insert 100 rows, then overwrite all with new values
    let mut values1 = Vec::new();
    let mut values2 = Vec::new();
    for i in 1..=100 {
        values1.push(format!("({i}, {i})")); // id=i, value=i
        values2.push(format!("({i}, {})", i * 10)); // id=i, value=i*10
    }

    sql_context
        .sql(&format!(
            "INSERT INTO paimon.test_db.t_large VALUES {}",
            values1.join(", ")
        ))
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    sql_context
        .sql(&format!(
            "INSERT INTO paimon.test_db.t_large VALUES {}",
            values2.join(", ")
        ))
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let count = row_count(&sql_context, "SELECT * FROM paimon.test_db.t_large").await;
    assert_eq!(count, 100, "Dedup should keep exactly 100 unique keys");

    // Spot-check a few values
    let rows = collect_id_value(
        &sql_context,
        "SELECT id, value FROM paimon.test_db.t_large WHERE id IN (1, 50, 100) ORDER BY id",
    )
    .await;
    assert_eq!(rows, vec![(1, 10), (50, 500), (100, 1000)]);
}

// ======================= Partitioned + Multi-Bucket =======================

/// Partitioned PK table with multiple buckets.
#[tokio::test]
async fn test_pk_partitioned_multi_bucket() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_part_mb (
                dt STRING, id INT NOT NULL, value INT,
                PRIMARY KEY (dt, id)
            ) PARTITIONED BY (dt)
            WITH ('bucket' = '2')",
        )
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_part_mb VALUES \
             ('2024-01-01', 1, 10), ('2024-01-01', 2, 20), \
             ('2024-01-01', 3, 30), ('2024-01-01', 4, 40), \
             ('2024-01-02', 1, 100), ('2024-01-02', 2, 200)",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Update across partitions
    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_part_mb VALUES \
             ('2024-01-01', 2, 222), ('2024-01-02', 1, 111)",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT dt, id, value FROM paimon.test_db.t_part_mb ORDER BY dt, id")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let mut rows = Vec::new();
    for batch in &batches {
        let dts = batch.column_by_name("dt").unwrap();
        let ids = batch
            .column_by_name("id")
            .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
            .unwrap();
        let vals = batch
            .column_by_name("value")
            .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
            .unwrap();
        for i in 0..batch.num_rows() {
            rows.push((
                string_value(dts.as_ref(), i).to_string(),
                ids.value(i),
                vals.value(i),
            ));
        }
    }

    assert_eq!(
        rows,
        vec![
            ("2024-01-01".to_string(), 1, 10),
            ("2024-01-01".to_string(), 2, 222),
            ("2024-01-01".to_string(), 3, 30),
            ("2024-01-01".to_string(), 4, 40),
            ("2024-01-02".to_string(), 1, 111),
            ("2024-01-02".to_string(), 2, 200),
        ]
    );
}

// ======================= Error Cases =======================

/// PK table with changelog-producer=input should write through DataFusion SQL.
#[tokio::test]
async fn test_pk_input_changelog_write_read() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_changelog (
                id INT NOT NULL, name STRING,
                PRIMARY KEY (id)
            ) WITH ('bucket' = '1', 'changelog-producer' = 'input')",
        )
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_changelog VALUES
                (1, 'alice'), (1, 'bob'), (2, 'carol')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let rows = collect_id_name(
        &sql_context,
        "SELECT id, name FROM paimon.test_db.t_changelog ORDER BY id",
    )
    .await;

    assert_eq!(rows, vec![(1, "bob".to_string()), (2, "carol".to_string())]);
}

// ======================= String Primary Key =======================

/// PK table with STRING primary key.
#[tokio::test]
async fn test_pk_string_key() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_strpk (
                code STRING NOT NULL, name STRING,
                PRIMARY KEY (code)
            ) WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_strpk VALUES \
             ('A001', 'alice'), ('B002', 'bob'), ('C003', 'carol')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Update A001
    sql_context
        .sql("INSERT INTO paimon.test_db.t_strpk VALUES ('A001', 'alice-v2')")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT code, name FROM paimon.test_db.t_strpk ORDER BY code")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let mut rows = Vec::new();
    for batch in &batches {
        let codes = batch.column_by_name("code").unwrap();
        let names = batch.column_by_name("name").unwrap();
        for i in 0..batch.num_rows() {
            rows.push((
                string_value(codes.as_ref(), i).to_string(),
                string_value(names.as_ref(), i).to_string(),
            ));
        }
    }

    assert_eq!(
        rows,
        vec![
            ("A001".to_string(), "alice-v2".to_string()),
            ("B002".to_string(), "bob".to_string()),
            ("C003".to_string(), "carol".to_string()),
        ]
    );
}

// ======================= Multiple Value Columns =======================

/// PK table with many value columns — verifies all columns survive dedup.
#[tokio::test]
async fn test_pk_multiple_value_columns() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_multi_val (
                id INT NOT NULL, col_a INT, col_b STRING, col_c INT,
                PRIMARY KEY (id)
            ) WITH ('bucket' = '1')",
        )
        .await
        .unwrap();

    sql_context
        .sql("INSERT INTO paimon.test_db.t_multi_val VALUES (1, 10, 'x', 100), (2, 20, 'y', 200)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    sql_context
        .sql("INSERT INTO paimon.test_db.t_multi_val VALUES (1, 11, 'xx', 111)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT id, col_a, col_b, col_c FROM paimon.test_db.t_multi_val ORDER BY id")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let mut rows = Vec::new();
    for batch in &batches {
        let ids = batch
            .column_by_name("id")
            .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
            .unwrap();
        let as_ = batch
            .column_by_name("col_a")
            .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
            .unwrap();
        let bs = batch.column_by_name("col_b").unwrap();
        let cs = batch
            .column_by_name("col_c")
            .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
            .unwrap();
        for i in 0..batch.num_rows() {
            rows.push((
                ids.value(i),
                as_.value(i),
                string_value(bs.as_ref(), i).to_string(),
                cs.value(i),
            ));
        }
    }

    assert_eq!(
        rows,
        vec![
            (1, 11, "xx".to_string(), 111), // updated
            (2, 20, "y".to_string(), 200),  // untouched
        ]
    );
}

// ======================= FirstRow Engine: INSERT OVERWRITE =======================

/// INSERT OVERWRITE on a partitioned FirstRow-engine PK table should delete
/// level-0 files. Before the fix, `skip_level_zero` was applied in the overwrite
/// scan path, causing level-0 files to survive the overwrite.
///
/// Verifies via TableScan (scan_all_files) that the overwrite correctly produces
/// delete entries for level-0 files, leaving only the new file per partition.
#[tokio::test]
async fn test_pk_first_row_insert_overwrite() {
    let (_tmp, catalog) = create_test_env();
    let sql_context = create_sql_context(catalog.clone()).await;
    sql_context
        .sql("CREATE SCHEMA paimon.test_db")
        .await
        .expect("CREATE SCHEMA failed");

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_fr_ow (
                dt STRING, id INT NOT NULL, name STRING,
                PRIMARY KEY (dt, id)
            ) PARTITIONED BY (dt)
            WITH ('bucket' = '1', 'merge-engine' = 'first-row')",
        )
        .await
        .unwrap();

    // First commit: two partitions, creates level-0 files
    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_fr_ow VALUES \
             ('2024-01-01', 1, 'alice'), ('2024-01-01', 2, 'bob'), \
             ('2024-01-02', 3, 'carol')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Verify via scan_all_files: 2 level-0 files (one per partition)
    let table = catalog
        .get_table(&Identifier::new("test_db", "t_fr_ow"))
        .await
        .unwrap();
    let plan = table
        .new_read_builder()
        .new_scan()
        .with_scan_all_files()
        .plan()
        .await
        .unwrap();
    let file_count: usize = plan.splits().iter().map(|s| s.data_files().len()).sum();
    assert_eq!(
        file_count, 2,
        "After INSERT: 2 level-0 files (one per partition)"
    );

    // INSERT OVERWRITE partition 2024-01-01 — must delete old level-0 file
    sql_context
        .sql("INSERT OVERWRITE paimon.test_db.t_fr_ow VALUES ('2024-01-01', 10, 'new_alice')")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let table = catalog
        .get_table(&Identifier::new("test_db", "t_fr_ow"))
        .await
        .unwrap();
    let plan = table
        .new_read_builder()
        .new_scan()
        .with_scan_all_files()
        .plan()
        .await
        .unwrap();
    let file_count: usize = plan.splits().iter().map(|s| s.data_files().len()).sum();
    assert_eq!(
        file_count, 2,
        "After OVERWRITE: 2 files (1 replaced for 2024-01-01 + 1 unchanged for 2024-01-02)"
    );

    // Second overwrite on the same partition — no stale files should accumulate
    sql_context
        .sql("INSERT OVERWRITE paimon.test_db.t_fr_ow VALUES ('2024-01-01', 20, 'newer_alice')")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let table = catalog
        .get_table(&Identifier::new("test_db", "t_fr_ow"))
        .await
        .unwrap();
    let plan = table
        .new_read_builder()
        .new_scan()
        .with_scan_all_files()
        .plan()
        .await
        .unwrap();
    let file_count: usize = plan.splits().iter().map(|s| s.data_files().len()).sum();
    assert_eq!(
        file_count, 2,
        "After second OVERWRITE: still 2 files (no stale level-0 files accumulated)"
    );
}

// ======================= Postpone Bucket (bucket = -2) =======================

/// Postpone bucket files are invisible to normal SELECT but visible via scan_all_files.
#[tokio::test]
async fn test_postpone_write_invisible_to_select() {
    let (_tmp, catalog) = create_test_env();
    let sql_context = create_sql_context(catalog.clone()).await;
    sql_context
        .sql("CREATE SCHEMA paimon.test_db")
        .await
        .expect("CREATE SCHEMA failed");

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_postpone (
                id INT NOT NULL, value INT,
                PRIMARY KEY (id)
            ) WITH ('bucket' = '-2')",
        )
        .await
        .unwrap();

    // Write data
    sql_context
        .sql("INSERT INTO paimon.test_db.t_postpone VALUES (1, 10), (2, 20), (3, 30)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // scan_all_files should find the postpone file
    let table = catalog
        .get_table(&Identifier::new("test_db", "t_postpone"))
        .await
        .unwrap();
    let plan = table
        .new_read_builder()
        .new_scan()
        .with_scan_all_files()
        .plan()
        .await
        .unwrap();
    let file_count: usize = plan.splits().iter().map(|s| s.data_files().len()).sum();
    assert_eq!(file_count, 1, "scan_all_files should find 1 postpone file");

    // Normal SELECT should return 0 rows (postpone files are invisible)
    let count = row_count(&sql_context, "SELECT * FROM paimon.test_db.t_postpone").await;
    assert_eq!(count, 0, "SELECT should return 0 rows for postpone table");
}

/// INSERT OVERWRITE on a postpone table should replace old files with new ones.
#[tokio::test]
async fn test_postpone_insert_overwrite() {
    let (_tmp, catalog) = create_test_env();
    let sql_context = create_sql_context(catalog.clone()).await;
    sql_context
        .sql("CREATE SCHEMA paimon.test_db")
        .await
        .expect("CREATE SCHEMA failed");

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_postpone_ow (
                id INT NOT NULL, value INT,
                PRIMARY KEY (id)
            ) WITH ('bucket' = '-2')",
        )
        .await
        .unwrap();

    // First commit
    sql_context
        .sql("INSERT INTO paimon.test_db.t_postpone_ow VALUES (1, 10), (2, 20)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let table = catalog
        .get_table(&Identifier::new("test_db", "t_postpone_ow"))
        .await
        .unwrap();
    let plan = table
        .new_read_builder()
        .new_scan()
        .with_scan_all_files()
        .plan()
        .await
        .unwrap();
    let file_count: usize = plan.splits().iter().map(|s| s.data_files().len()).sum();
    assert_eq!(file_count, 1, "After INSERT: 1 postpone file");

    // INSERT OVERWRITE should replace old file
    sql_context
        .sql("INSERT OVERWRITE paimon.test_db.t_postpone_ow VALUES (3, 30)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let table = catalog
        .get_table(&Identifier::new("test_db", "t_postpone_ow"))
        .await
        .unwrap();
    let plan = table
        .new_read_builder()
        .new_scan()
        .with_scan_all_files()
        .plan()
        .await
        .unwrap();
    let file_count: usize = plan.splits().iter().map(|s| s.data_files().len()).sum();
    assert_eq!(
        file_count, 1,
        "After OVERWRITE: only 1 new file (old file deleted)"
    );
}

// ======================= Bucket Keys Regression =======================

/// Regression: partitioned PK fixed-bucket table — query with partition + PK
/// predicate must return rows. Before the fix, `bucket_keys()` returned full
/// primary keys (including partition columns), while the read path used
/// `trimmed_primary_keys()`, causing bucket pruning to target the wrong bucket.
#[tokio::test]
async fn test_pk_partitioned_fixed_bucket_predicate_query() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_bk_pred (
                pt STRING, id INT NOT NULL, value INT,
                PRIMARY KEY (pt, id)
            ) PARTITIONED BY (pt)
            WITH ('bucket' = '2')",
        )
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_bk_pred VALUES \
             ('a', 1, 10), ('a', 2, 20), ('b', 3, 30), ('b', 4, 40)",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Query with both partition and PK columns in predicate
    let rows = collect_id_value(
        &sql_context,
        "SELECT id, value FROM paimon.test_db.t_bk_pred WHERE pt = 'a' AND id = 1",
    )
    .await;
    assert_eq!(rows, vec![(1, 10)], "Predicate query must find the row");

    let rows = collect_id_value(
        &sql_context,
        "SELECT id, value FROM paimon.test_db.t_bk_pred WHERE pt = 'b' AND id = 4",
    )
    .await;
    assert_eq!(rows, vec![(4, 40)], "Predicate query must find the row");
}

// ======================= DV + Deduplicate Regression =======================

/// Regression: DV-enabled Deduplicate PK table must not error on read.
/// Before the fix, removing the DV guard caused level-0 files to reach
/// KeyValueFileReader which rejects deletion-vector files with a hard error.
/// With the guard restored, level-0 files are skipped in scan (DV mode relies
/// on compaction to produce higher-level files).
#[tokio::test]
async fn test_pk_dv_deduplicate_read_no_error() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_dv_dedup (
                id INT NOT NULL, value INT,
                PRIMARY KEY (id)
            ) WITH ('bucket' = '1', 'deletion-vectors.enabled' = 'true')",
        )
        .await
        .unwrap();

    sql_context
        .sql("INSERT INTO paimon.test_db.t_dv_dedup VALUES (1, 10), (2, 20)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Second commit with overlapping key — creates level-0 files
    sql_context
        .sql("INSERT INTO paimon.test_db.t_dv_dedup VALUES (2, 200), (3, 30)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Read must not error. DV mode skips level-0 files, so only compacted
    // (level > 0) files are visible. Without compaction, all files are level-0
    // and get skipped — count may be 0, but the read must succeed without error.
    // Before the fix, this would hard-fail with "KeyValueFileReader does not
    // support deletion vectors".
    let result = sql_context
        .sql("SELECT * FROM paimon.test_db.t_dv_dedup")
        .await
        .unwrap()
        .collect()
        .await;
    assert!(
        result.is_ok(),
        "DV + Deduplicate read should not error: {:?}",
        result.err()
    );
}

// ======================= Cross-Split Merge Correctness =======================

/// Regression: a 1-byte split target forces every data file into its own
/// split candidate. Files holding versions of the same key overlap on key
/// range and must still be merged into a single row — previously each split
/// emitted its own (stale) version.
#[tokio::test]
async fn test_pk_dedup_merges_across_tiny_splits() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_tiny_split (
                id INT NOT NULL, value INT,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'source.split.target-size' = '1b',
                'source.split.open-file-cost' = '1b'
            )",
        )
        .await
        .unwrap();

    for value in [10, 20, 30] {
        sql_context
            .sql(&format!(
                "INSERT INTO paimon.test_db.t_tiny_split VALUES (1, {value})"
            ))
            .await
            .unwrap()
            .collect()
            .await
            .unwrap();
    }

    let rows = collect_id_value(
        &sql_context,
        "SELECT id, value FROM paimon.test_db.t_tiny_split",
    )
    .await;
    assert_eq!(rows, vec![(1, 30)]);
}

/// LIMIT must not be starved by merge-needed splits: the three versions of
/// key 1 share one split whose physical row count (3) overstates its single
/// logical row. Such splits report an unknown merged row count, so limit
/// pushdown cannot stop before the split holding key 2.
#[tokio::test]
async fn test_pk_limit_not_starved_by_merge_splits() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_tiny_split_limit (
                id INT NOT NULL, value INT,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'source.split.target-size' = '1b',
                'source.split.open-file-cost' = '1b'
            )",
        )
        .await
        .unwrap();

    // Three versions of key 1 (one overlapping section), then key 2.
    for value in [10, 20, 30] {
        sql_context
            .sql(&format!(
                "INSERT INTO paimon.test_db.t_tiny_split_limit VALUES (1, {value})"
            ))
            .await
            .unwrap()
            .collect()
            .await
            .unwrap();
    }
    sql_context
        .sql("INSERT INTO paimon.test_db.t_tiny_split_limit VALUES (2, 200)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // Two logical rows exist; LIMIT 2 must return both.
    let returned = row_count(
        &sql_context,
        "SELECT id, value FROM paimon.test_db.t_tiny_split_limit LIMIT 2",
    )
    .await;
    assert_eq!(returned, 2, "LIMIT 2 must yield 2 rows");

    // COUNT(*) must reflect logical rows, not the physical (pre-merge) count
    // that DataFusion could otherwise read from exact scan statistics.
    let batches = sql_context
        .sql("SELECT COUNT(*) FROM paimon.test_db.t_tiny_split_limit")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();
    let count = batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<datafusion::arrow::array::Int64Array>()
        .unwrap()
        .value(0);
    assert_eq!(count, 2, "COUNT(*) must count merged rows");
}

/// Partial-update files can hold several physical rows of one key (the
/// writer keeps all rows for read-side field-wise merge), so their splits
/// must never report physical row counts as merged row counts: COUNT(*) has
/// to count merged rows and LIMIT must not be starved.
#[tokio::test]
async fn test_pk_partial_update_count_and_limit_see_merged_rows() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_pu_count (
                id INT NOT NULL, v_int INT, v_str STRING,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'merge-engine' = 'partial-update',
                'source.split.target-size' = '1b',
                'source.split.open-file-cost' = '1b'
            )",
        )
        .await
        .unwrap();

    // One INSERT writes three partial updates of key 1 into a single file,
    // plus an independent key 2.
    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_pu_count VALUES
             (1, 10, CAST(NULL AS STRING)),
             (1, CAST(NULL AS INT), 'hello'),
             (1, 100, CAST(NULL AS STRING)),
             (2, 200, 'world')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // COUNT(*) must count merged rows, not the physical rows a single file
    // holds (DataFusion may answer COUNT(*) from exact scan statistics).
    let batches = sql_context
        .sql("SELECT COUNT(*) FROM paimon.test_db.t_pu_count")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();
    let count = batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<datafusion::arrow::array::Int64Array>()
        .unwrap()
        .value(0);
    assert_eq!(count, 2, "COUNT(*) must count merged rows");

    // Two logical rows exist; LIMIT 2 must not be starved by the
    // multi-version file of key 1.
    let returned = row_count(
        &sql_context,
        "SELECT id, v_int FROM paimon.test_db.t_pu_count LIMIT 2",
    )
    .await;
    assert_eq!(returned, 2, "LIMIT 2 must yield 2 rows");
}

/// Same regression for the partial-update engine: per-column updates of one
/// key spread over three commits/files must merge into a single row even
/// when the split target would otherwise separate the files.
#[tokio::test]
async fn test_pk_partial_update_merges_across_tiny_splits() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_tiny_split_pu (
                id INT NOT NULL, v_int INT, v_str STRING,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'merge-engine' = 'partial-update',
                'source.split.target-size' = '1b',
                'source.split.open-file-cost' = '1b'
            )",
        )
        .await
        .unwrap();

    sql_context
        .sql("INSERT INTO paimon.test_db.t_tiny_split_pu VALUES (1, 10, CAST(NULL AS STRING))")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();
    sql_context
        .sql("INSERT INTO paimon.test_db.t_tiny_split_pu VALUES (1, CAST(NULL AS INT), 'hello')")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();
    sql_context
        .sql("INSERT INTO paimon.test_db.t_tiny_split_pu VALUES (1, 100, CAST(NULL AS STRING))")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT id, v_int, v_str FROM paimon.test_db.t_tiny_split_pu")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();
    assert_eq!(
        collect_int_int_str(&batches),
        vec![(1, 100, "hello".to_string())]
    );
}

// ======================= Aggregation Engine =======================

/// Basic: aggregation engine sums numeric column and concatenates string
/// column across overlapping primary keys.
#[tokio::test]
async fn test_pk_aggregation_sum_and_listagg_fixed_multi_bucket_e2e() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_agg_sum (
                id INT NOT NULL, amount INT, tag STRING,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '4',
                'merge-engine' = 'aggregation',
                'fields.amount.aggregate-function' = 'sum',
                'fields.tag.aggregate-function' = 'listagg',
                'fields.tag.list-agg-delimiter' = '|'
            )",
        )
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_agg_sum VALUES \
             (1, 10, 'a'), (2, 20, 'x')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_agg_sum VALUES \
             (1, 5, 'b'), (2, 7, CAST(NULL AS STRING)), (3, 99, 'solo')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT id, amount, tag FROM paimon.test_db.t_agg_sum ORDER BY id")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let mut rows: Vec<(i32, Option<i32>, Option<String>)> = Vec::new();
    for batch in &batches {
        let ids = batch
            .column_by_name("id")
            .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
            .unwrap();
        let amounts = batch
            .column_by_name("amount")
            .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
            .unwrap();
        let tags = batch.column_by_name("tag").unwrap();
        for i in 0..batch.num_rows() {
            rows.push((
                ids.value(i),
                if amounts.is_null(i) {
                    None
                } else {
                    Some(amounts.value(i))
                },
                if tags.is_null(i) {
                    None
                } else {
                    Some(string_value(tags.as_ref(), i).to_string())
                },
            ));
        }
    }

    assert_eq!(
        rows,
        vec![
            (1, Some(15), Some("a|b".to_string())),
            (2, Some(27), Some("x".to_string())),
            (3, Some(99), Some("solo".to_string())),
        ]
    );
}

/// `fields.default-aggregate-function` applies to any column without an
/// explicit per-field aggregator.
#[tokio::test]
async fn test_pk_aggregation_default_function() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_agg_default (
                id INT NOT NULL, a INT, b STRING,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'merge-engine' = 'aggregation',
                'fields.default-aggregate-function' = 'last_non_null_value'
            )",
        )
        .await
        .unwrap();

    sql_context
        .sql("INSERT INTO paimon.test_db.t_agg_default VALUES (1, 10, 'old')")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();
    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_agg_default VALUES \
             (1, CAST(NULL AS INT), 'new')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();
    sql_context
        .sql("INSERT INTO paimon.test_db.t_agg_default VALUES (1, 99, CAST(NULL AS STRING))")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT id, a, b FROM paimon.test_db.t_agg_default")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 1);
    let batch = &batches[0];
    let id = batch
        .column_by_name("id")
        .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
        .unwrap();
    let a = batch
        .column_by_name("a")
        .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
        .unwrap();
    let b = batch.column_by_name("b").unwrap();
    assert_eq!(id.value(0), 1);
    assert_eq!(a.value(0), 99); // latest non-null int across the three commits
    assert_eq!(string_value(b.as_ref(), 0), "new"); // latest non-null string
}

/// Mixed aggregators in a single table: sum / max / bool_or / first_non_null_value.
#[tokio::test]
async fn test_pk_aggregation_mixed_aggregators() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_agg_mixed (
                id INT NOT NULL, total INT, peak INT, ok BOOLEAN, first_seen STRING,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'merge-engine' = 'aggregation',
                'fields.total.aggregate-function' = 'sum',
                'fields.peak.aggregate-function' = 'max',
                'fields.ok.aggregate-function' = 'bool_or',
                'fields.first_seen.aggregate-function' = 'first_non_null_value'
            )",
        )
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_agg_mixed VALUES \
             (1, 10, 5, false, 'a'), \
             (1, 5, 8, true, 'b'), \
             (1, 3, 7, false, 'c')",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT id, total, peak, ok, first_seen FROM paimon.test_db.t_agg_mixed")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    use datafusion::arrow::array::BooleanArray;
    assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 1);
    let batch = &batches[0];
    let total = batch
        .column_by_name("total")
        .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
        .unwrap();
    let peak = batch
        .column_by_name("peak")
        .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
        .unwrap();
    let ok = batch
        .column_by_name("ok")
        .and_then(|c| c.as_any().downcast_ref::<BooleanArray>())
        .unwrap();
    let first_seen = batch.column_by_name("first_seen").unwrap();
    assert_eq!(total.value(0), 18); // 10 + 5 + 3
    assert_eq!(peak.value(0), 8); // max(5, 8, 7)
    assert!(ok.value(0)); // bool_or = true if any is true
    assert_eq!(string_value(first_seen.as_ref(), 0), "a"); // first non-null wins
}

/// `sequence.field` forces the named column to `last_value`, even when a
/// table-level default aggregator would otherwise apply.
#[tokio::test]
async fn test_pk_aggregation_sequence_field_forced_last_value() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_agg_seq (
                id INT NOT NULL, amount INT, ts INT,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'merge-engine' = 'aggregation',
                'sequence.field' = 'ts',
                'fields.amount.aggregate-function' = 'sum',
                'fields.default-aggregate-function' = 'sum'
            )",
        )
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_agg_seq VALUES \
             (1, 10, 100), (1, 20, 250)",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT id, amount, ts FROM paimon.test_db.t_agg_seq")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 1);
    let batch = &batches[0];
    let amount = batch
        .column_by_name("amount")
        .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
        .unwrap();
    let ts = batch
        .column_by_name("ts")
        .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
        .unwrap();
    assert_eq!(amount.value(0), 30); // sum still applies
    assert_eq!(ts.value(0), 250); // forced last_value over default sum
}

/// Aggregation engine reads must surface Unsupported when a DELETE/UPDATE
/// row appears.
#[tokio::test]
async fn test_pk_aggregation_rejects_delete() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_agg_del (
                id INT NOT NULL, amount INT,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'merge-engine' = 'aggregation',
                'fields.amount.aggregate-function' = 'sum'
            )",
        )
        .await
        .unwrap();

    sql_context
        .sql("INSERT INTO paimon.test_db.t_agg_del VALUES (1, 10), (2, 20)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    // DELETE may either fail at planning or surface Unsupported at execution.
    // Either way the error must mention the aggregation engine refusing the
    // retract row; we explicitly assert both branches so a future parser
    // change cannot silently turn this into a no-op pass.
    let plan_result = sql_context
        .sql("DELETE FROM paimon.test_db.t_agg_del WHERE id = 1")
        .await;
    match plan_result {
        Ok(df) => {
            let exec = df.collect().await;
            assert!(exec.is_err(), "DELETE on aggregation table should fail");
            let msg = format!("{:?}", exec.err().unwrap());
            assert!(
                msg.contains("aggregation")
                    || msg.contains("DELETE")
                    || msg.contains("UPDATE_BEFORE"),
                "expected aggregation engine to reject DELETE at execution, got {msg}"
            );
        }
        Err(e) => {
            let msg = format!("{e:?}");
            assert!(
                msg.contains("aggregation")
                    || msg.contains("DELETE")
                    || msg.contains("Unsupported"),
                "expected aggregation engine to reject DELETE at planning, got {msg}"
            );
        }
    }
}

/// `merge-engine=aggregation` with no per-field nor default aggregate-function
/// should still work: each value column falls back to `last_non_null_value`,
/// matching Java `AggregateMergeFunction#getAggFuncName`.
#[tokio::test]
async fn test_pk_aggregation_default_fallback_is_last_non_null_value() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_agg_fallback (
                id INT NOT NULL, amount INT,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'merge-engine' = 'aggregation'
            )",
        )
        .await
        .unwrap();

    sql_context
        .sql("INSERT INTO paimon.test_db.t_agg_fallback VALUES (1, 10), (1, 20)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT id, amount FROM paimon.test_db.t_agg_fallback")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();
    assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 1);
    let amount = batches[0]
        .column_by_name("amount")
        .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
        .unwrap();
    assert_eq!(amount.value(0), 20); // last_non_null_value
}

/// CREATE TABLE should reject unsupported aggregation knobs in basic mode.
#[tokio::test]
async fn test_pk_aggregation_rejects_unsupported_options_at_create() {
    let (_tmp, sql_context) = setup_sql_context().await;

    let err = sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_agg_bad (
                id INT NOT NULL, amount INT,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'merge-engine' = 'aggregation',
                'fields.amount.aggregate-function' = 'sum',
                'fields.amount.ignore-retract' = 'true'
            )",
        )
        .await
        .expect_err("CREATE TABLE with ignore-retract should fail in basic mode");
    let msg = format!("{err:?}");
    assert!(
        msg.contains("ignore-retract"),
        "expected create-time rejection to mention ignore-retract, got {msg}"
    );
}

/// CREATE TABLE should reject `fields.<typo>.aggregate-function` referring to
/// a non-existent column, so misconfigured aggregation metadata cannot be
/// persisted.
#[tokio::test]
async fn test_pk_aggregation_create_table_rejects_unknown_field() {
    let (_tmp, sql_context) = setup_sql_context().await;

    let err = sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_agg_typo (
                id INT NOT NULL, amount INT,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'merge-engine' = 'aggregation',
                'fields.amout.aggregate-function' = 'sum'
            )",
        )
        .await
        .expect_err("CREATE TABLE with unknown field should fail at create time");
    let msg = format!("{err:?}");
    assert!(
        msg.contains("amout") && msg.contains("amount"),
        "expected unknown-field error to name the typo and surface the available \
         columns, got {msg}"
    );
}

/// CREATE TABLE should reject `fields.<col>.aggregate-function = '<unknown>'`
/// at create time rather than only failing the first SELECT.
#[tokio::test]
async fn test_pk_aggregation_create_table_rejects_unknown_function() {
    let (_tmp, sql_context) = setup_sql_context().await;

    let err = sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_agg_badfn (
                id INT NOT NULL, amount INT,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'merge-engine' = 'aggregation',
                'fields.amount.aggregate-function' = 'sume'
            )",
        )
        .await
        .expect_err("CREATE TABLE with unknown function should fail at create time");
    let msg = format!("{err:?}");
    assert!(
        msg.contains("sume"),
        "expected unknown-function error to surface the bad name, got {msg}"
    );
}

/// CREATE TABLE should reject aggregate-function/column type incompatibility
/// (e.g. `sum` on a STRING column) at create time.  This is stricter than
/// Java upstream, which defers the check to the first read/write.
#[tokio::test]
async fn test_pk_aggregation_create_table_rejects_incompatible_type() {
    let (_tmp, sql_context) = setup_sql_context().await;

    let err = sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_agg_badtype (
                id INT NOT NULL, tag STRING,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'merge-engine' = 'aggregation',
                'fields.tag.aggregate-function' = 'sum'
            )",
        )
        .await
        .expect_err("CREATE TABLE with incompatible function/type should fail at create time");
    let msg = format!("{err:?}");
    assert!(
        msg.contains("sum") && msg.contains("tag"),
        "expected incompatible-type error to mention the function and field, got {msg}"
    );
}

/// CREATE TABLE must reject per-field aggregation on a sequence field,
/// matching Java schema validation.
#[tokio::test]
async fn test_pk_aggregation_create_table_rejects_sequence_field_function() {
    let (_tmp, sql_context) = setup_sql_context().await;

    let err = sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_agg_seq_bad (
                id INT NOT NULL, amount INT, v INT,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'merge-engine' = 'aggregation',
                'sequence.field' = 'amount',
                'fields.amount.aggregate-function' = 'listagg',
                'fields.v.aggregate-function' = 'sum'
            )",
        )
        .await
        .expect_err("CREATE TABLE with aggregation on sequence.field should fail");
    let msg = format!("{err:?}");
    assert!(
        msg.contains("sequence field") && msg.contains("amount"),
        "expected sequence-field aggregation rejection, got {msg}"
    );
}

/// CREATE TABLE must accept a function/type pair that the runtime ignores for
/// primary-key columns: PK fields are copied through, so type compatibility is
/// not checked for them.
#[tokio::test]
async fn test_pk_aggregation_create_table_accepts_ignored_function_on_pk() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_agg_pk_ok (
                id INT NOT NULL, v INT,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'merge-engine' = 'aggregation',
                'fields.id.aggregate-function' = 'listagg',
                'fields.v.aggregate-function' = 'sum'
            )",
        )
        .await
        .expect("CREATE TABLE with runtime-ignored PK function/type pair should succeed");
}

/// All-NULL aggregation group on a nullable `sum` column should emit NULL
/// rather than 0 or an error: nothing was observed, so there is no
/// arithmetic result to surface.
#[tokio::test]
async fn test_pk_aggregation_sum_all_null_emits_null_for_nullable_column() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_agg_null (
                id INT NOT NULL, amount INT,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'merge-engine' = 'aggregation',
                'fields.amount.aggregate-function' = 'sum'
            )",
        )
        .await
        .unwrap();

    sql_context
        .sql(
            "INSERT INTO paimon.test_db.t_agg_null VALUES \
             (1, CAST(NULL AS INT)), (1, CAST(NULL AS INT))",
        )
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT id, amount FROM paimon.test_db.t_agg_null")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 1);
    let amount = batches[0]
        .column_by_name("amount")
        .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
        .unwrap();
    assert!(amount.is_null(0), "sum over all-NULL group should be NULL");
}

/// Regression guard: end-to-end SELECT on an aggregation table must traverse
/// the KeyValueFileReader path (TableRead::to_arrow → read_pk → read_kv),
/// not silently fall through to read_raw.  The basic correctness assertion
/// (sum aggregation) implies this routing — a fallthrough to read_raw would
/// return the raw rows unmerged, breaking the sum.
#[tokio::test]
async fn test_pk_aggregation_routing_uses_kv_path() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_agg_route (
                id INT NOT NULL, amount INT,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'merge-engine' = 'aggregation',
                'fields.amount.aggregate-function' = 'sum'
            )",
        )
        .await
        .unwrap();

    // Two rows with the same key in a single INSERT — read_raw would return 2
    // rows; read_kv (with AggregateMergeFunction) collapses them into 1 with
    // amount=30.
    sql_context
        .sql("INSERT INTO paimon.test_db.t_agg_route VALUES (1, 10), (1, 20)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let n = row_count(&sql_context, "SELECT * FROM paimon.test_db.t_agg_route").await;
    assert_eq!(
        n, 1,
        "aggregation table must collapse same-PK rows; got {n} rows which suggests \
         to_arrow fell through to read_raw"
    );
    let batches = sql_context
        .sql("SELECT amount FROM paimon.test_db.t_agg_route")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();
    let amount = batches[0]
        .column_by_name("amount")
        .and_then(|c| c.as_any().downcast_ref::<Int32Array>())
        .unwrap();
    assert_eq!(amount.value(0), 30);
}

/// Regression: `COUNT(*)` pushes an empty projection down to the scan, so the
/// KV merge read path must preserve the row count when reordering a batch with
/// zero columns. Aggregation tables route through that path; without an
/// explicit `with_row_count`, the reordered batch would report 0 rows and
/// `COUNT(*)` would collapse to 0 even though the merge produced rows.
#[tokio::test]
async fn test_pk_aggregation_count_star_empty_projection() {
    let (_tmp, sql_context) = setup_sql_context().await;

    sql_context
        .sql(
            "CREATE TABLE paimon.test_db.t_agg_count (
                id INT NOT NULL, amount INT,
                PRIMARY KEY (id)
            ) WITH (
                'bucket' = '1',
                'merge-engine' = 'aggregation',
                'fields.amount.aggregate-function' = 'sum'
            )",
        )
        .await
        .unwrap();

    // Two commits with overlapping primary keys so the read path must merge:
    // raw row count is 5, but the table holds 3 distinct keys (1, 2, 3).
    sql_context
        .sql("INSERT INTO paimon.test_db.t_agg_count VALUES (1, 10), (2, 20)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();
    sql_context
        .sql("INSERT INTO paimon.test_db.t_agg_count VALUES (1, 5), (2, 7), (3, 99)")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();

    let batches = sql_context
        .sql("SELECT COUNT(*) FROM paimon.test_db.t_agg_count")
        .await
        .unwrap()
        .collect()
        .await
        .unwrap();
    let count = batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<Int64Array>()
        .unwrap();
    assert_eq!(
        count.value(0),
        3,
        "COUNT(*) over an aggregation table must reflect merged rows; a 0/wrong \
         count means the empty-projection reorder dropped the row count"
    );
}