ormer 0.2.14

A minimalist ORM framework that supports SQLite, PostgreSQL, MySQL, and SqlServer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
#![allow(clippy::upper_case_acronyms)]

#[cfg(feature = "clickhouse")]
use super::SingleSqlStatement;
/// 统一的数据库抽象层
/// 使用枚举包装不同数据库后端,对外提供统一接口
/// 通过条件编译控制枚举变体
use super::connection_pool;
use super::{SqlStatement, common_helpers};
use super::super::capabilities::Capabilities;
use crate::db_first;
use crate::model::{
    Model, NoInclude, Relation, RelationHandle, RelationInfo, RelationPathInfo, RelationQuery,
    RelationSelection, TableRouteValue, ThroughRelation, Tracked, Value, WritableModel,
    routed_model_table_name_for_db,
};
#[cfg(any(feature = "clickhouse", feature = "influxdb"))]
use crate::query::builder::Select;
#[cfg(feature = "clickhouse")]
use crate::query::builder::ProjectionSelect;
use crate::query::builder::{
    ContextFilter, DerivedSelect, DerivedTableSelect, FilterQuery, NamedFilterQuery, WhereExpr,
    WithoutFilterQuery,
};
use crate::query::filter::FilterExpr;
use crate::query::insert::{IntoInsertAssignment, IntoInsertDefaultColumn};
use crate::raw_sql::{IntoRawSql, RawSql};
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};

pub type TransactionFuture<'a, R> = Pin<Box<dyn Future<Output = crate::Result<R>> + Send + 'a>>;
pub type BatchQueryFuture<'a, T> = Pin<Box<dyn Future<Output = crate::Result<T>> + Send + 'a>>;

static SAVEPOINT_COUNTER: AtomicUsize = AtomicUsize::new(0);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IsolationLevel {
    ReadUncommitted,
    ReadCommitted,
    RepeatableRead,
    Serializable,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct TransactionOptions {
    pub isolation: Option<IsolationLevel>,
    pub read_only: bool,
}

impl TransactionOptions {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn isolation(mut self, isolation: IsolationLevel) -> Self {
        self.isolation = Some(isolation);
        self
    }

    pub fn read_only(mut self) -> Self {
        self.read_only = true;
        self
    }

    pub fn serializable() -> Self {
        Self::new().isolation(IsolationLevel::Serializable)
    }
}

pub struct BatchFuture<'a, B> {
    batch: B,
    _marker: std::marker::PhantomData<&'a ()>,
}

impl<'a, B> BatchFuture<'a, B> {
    pub(crate) fn new(batch: B) -> Self {
        Self {
            batch,
            _marker: std::marker::PhantomData,
        }
    }
}

impl<'a, B> std::future::IntoFuture for BatchFuture<'a, B>
where
    B: BatchQueries<'a> + Send + 'a,
{
    type Output = crate::Result<B::Output>;
    type IntoFuture = BatchQueryFuture<'a, B::Output>;

    fn into_future(self) -> Self::IntoFuture {
        self.batch.into_batch_future()
    }
}

pub struct BatchManyFuture<'a, Q> {
    queries: Vec<Q>,
    _marker: std::marker::PhantomData<&'a ()>,
}

impl<'a, Q> BatchManyFuture<'a, Q> {
    pub(crate) fn new<I>(queries: I) -> Self
    where
        I: IntoIterator<Item = Q>,
    {
        Self {
            queries: queries.into_iter().collect(),
            _marker: std::marker::PhantomData,
        }
    }
}

impl<'a, Q> std::future::IntoFuture for BatchManyFuture<'a, Q>
where
    Q: BatchQuery<'a> + Send + 'a,
{
    type Output = crate::Result<Vec<Q::Output>>;
    type IntoFuture = BatchQueryFuture<'a, Vec<Q::Output>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let mut results = Vec::with_capacity(self.queries.len());
            for query in self.queries {
                results.push(query.into_batch_future().await?);
            }
            Ok(results)
        })
    }
}

pub trait BatchQuery<'a>: Sized {
    type Output: Send + 'a;

    fn into_batch_future(self) -> BatchQueryFuture<'a, Self::Output>;
}

pub trait BatchQueries<'a>: Sized {
    type Output: Send + 'a;

    fn into_batch_future(self) -> BatchQueryFuture<'a, Self::Output>;
}

macro_rules! impl_batch_tuple {
    ($($name:ident => $var:ident),+ $(,)?) => {
        impl<'a, $($name,)+> BatchQueries<'a> for ($($name,)+)
        where
            $($name: BatchQuery<'a> + Send + 'a,)+
        {
            type Output = ($($name::Output,)+);

            fn into_batch_future(self) -> BatchQueryFuture<'a, Self::Output> {
                let ($($var,)+) = self;
                Box::pin(async move {
                    $(
                        let $var = $var.into_batch_future().await?;
                    )+
                    Ok(($($var,)+))
                })
            }
        }
    };
}

impl<'a> BatchQueries<'a> for () {
    type Output = ();

    fn into_batch_future(self) -> BatchQueryFuture<'a, Self::Output> {
        Box::pin(async { Ok(()) })
    }
}

impl_batch_tuple!(A => a);
impl_batch_tuple!(A => a, B => b);
impl_batch_tuple!(A => a, B => b, C => c);
impl_batch_tuple!(A => a, B => b, C => c, D => d);
impl_batch_tuple!(A => a, B => b, C => c, D => d, E => e);
impl_batch_tuple!(A => a, B => b, C => c, D => d, E => e, F => f);
impl_batch_tuple!(A => a, B => b, C => c, D => d, E => e, F => f, G => g);
impl_batch_tuple!(A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h);

// 根据启用的 feature 导入后端实现
#[cfg(feature = "sqlite")]
use super::super::sqlite_backend;

#[cfg(feature = "postgresql")]
use super::super::postgresql_backend;

#[cfg(feature = "mysql")]
use super::super::mysql_backend;

#[cfg(feature = "mssql")]
use super::super::mssql_backend;

#[cfg(feature = "duckdb")]
use super::super::duckdb_backend;

#[cfg(feature = "clickhouse")]
use super::super::clickhouse_backend;

#[cfg(feature = "influxdb")]
use super::super::influxdb_backend;

fn relation_filter_values(values: Vec<Value>) -> Vec<crate::query::filter::Value> {
    let mut seen = std::collections::HashSet::new();
    values
        .into_iter()
        .filter(|value| !matches!(value, Value::Null))
        .filter(|value| seen.insert(common_helpers::model_value_key(value)))
        .collect()
}

#[allow(dead_code)]
fn unsupported_feature(backend: super::super::DbType, feature: &'static str) -> crate::OrmerError {
    crate::OrmerError::UnsupportedFeature { backend, feature }
}

/// 计算待应用迁移:按版本排序、重复版本报错、已应用迁移的 checksum 漂移报错。
/// ClickHouse 与 InfluxDB 的 HTTP 迁移路径共用(两者均无事务,历史由各自端点维护)。
#[cfg(any(feature = "clickhouse", feature = "influxdb"))]
pub(crate) fn compute_pending_migrations<M: crate::migration::Migration>(
    applied: Vec<crate::migration::MigrationInfo>,
    migrations: &[M],
) -> crate::Result<Vec<crate::migration::MigrationInfo>> {
    let applied = applied
        .into_iter()
        .map(|migration| (migration.version, migration.checksum))
        .collect::<std::collections::BTreeMap<_, _>>();
    let mut sorted = migrations.iter().collect::<Vec<_>>();
    sorted.sort_by_key(|migration| migration.version());
    let mut seen = std::collections::BTreeSet::new();
    let mut pending = Vec::new();
    for migration in sorted {
        if !seen.insert(migration.version()) {
            return Err(crate::ormer_error!(
                "Duplicate migration version {}",
                migration.version()
            ));
        }
        if let Some(checksum) = applied.get(&migration.version()) {
            if *checksum != migration.checksum() {
                return Err(crate::ormer_error!(
                    "Migration {} checksum changed after it was applied",
                    migration.version()
                ));
            }
            continue;
        }
        pending.push(crate::migration::MigrationInfo {
            version: migration.version(),
            name: migration.name().to_string(),
            checksum: migration.checksum(),
        });
    }
    Ok(pending)
}

pub(crate) fn primary_key_filter<T: Model>(
    key: impl crate::model::PrimaryKey,
) -> crate::Result<WhereExpr> {
    let pk_columns = T::primary_key_columns();
    let pk_values = key.into_values();

    if pk_columns.is_empty() {
        return Err(crate::ormer_error!(
            "Model {} does not have a primary key",
            T::TABLE_NAME
        ));
    }
    if pk_columns.len() != pk_values.len() {
        return Err(crate::ormer_error!(
            "Primary key column count ({}) does not match value count ({})",
            pk_columns.len(),
            pk_values.len()
        ));
    }

    let filters = common_helpers::primary_key_filter_exprs(pk_columns, pk_values);
    let Some(filter) = common_helpers::and_filter_exprs(filters) else {
        return Err(crate::ormer_error!(
            "Model {} does not have a primary key filter",
            T::TABLE_NAME
        ));
    };

    Ok(WhereExpr::from_filter(filter))
}

pub(crate) fn relation_owner_key(path: RelationPathInfo) -> &'static RelationInfo {
    match path {
        RelationPathInfo::Direct { relation } => relation,
        RelationPathInfo::Through { via_relation, .. } => via_relation,
    }
}

/// find_by_id 家族的公共尾部(L26):主键过滤 → `range(..1)` → collect →
/// 取首行。Database / DatabaseScope / Transaction / TransactionScope /
/// 池连接 PooledDatabaseScope 五个入口共用,各入口只负责构造带各自
/// context filters 的 [`SelectExecutor`]。
pub(crate) async fn find_by_id_with_executor<T>(
    exec: SelectExecutor<'_, T>,
    key: impl crate::model::PrimaryKey,
) -> crate::Result<Option<T>>
where
    T: Model + 'static + Send + Sync,
{
    let where_expr = primary_key_filter::<T>(key)?;
    let results = exec
        .filter(|_| where_expr)
        .range(..1)
        .collect::<Vec<T>>()
        .await?;
    Ok(results.into_iter().next())
}

/// find_related 的公共尾部(L26):解析 owner key 后走关联查询执行器。
pub(crate) async fn find_related_with_executor<'a, T, S>(
    exec: &SelectExecutor<'a, T>,
    owner: &T,
    relation: &S,
) -> crate::Result<Vec<S::Target>>
where
    T: Model + 'static + Send + Sync,
    S: RelationSelection<T> + RelationNestedLoader<'a, T> + Send + Sync,
    S::Target: Send + Sync,
    S::Via: Send + Sync,
{
    let path = relation.path_info()?;
    let key = owner.relation_key_value(relation_owner_key(path))?;
    exec.select_related_with_selection(vec![key], relation).await
}

/// preload 的公共尾部(L26):批量预加载关联对象,避免 N+1。
pub(crate) async fn preload_with_executor<'a, T, S>(
    exec: &SelectExecutor<'a, T>,
    owners: &mut [T],
    relation: S,
) -> crate::Result<()>
where
    T: Model + 'static + Send + Sync,
    S: RelationSelection<T> + RelationNestedLoader<'a, T> + Send + Sync,
    S::Target: Send + Sync,
    S::Via: Send + Sync,
{
    exec.preload_models_with_selection(owners, relation).await
}

/// select_column 家族([`Database::select_column`] / 池连接
/// `DbExecutor::select_column` / [`SelectExecutor::select_column`])对
/// ClickHouse 协议后端的统一能力判定(L19:三个入口共用同一判定与文案)。
///
/// 以 `Capabilities::advanced_grouping` 为准:ClickHouse 支持聚合投影
/// (矩阵为 true,放行走分组聚合执行分支);InfluxDB 不支持(InfluxQL
/// 的 GROUP BY 仅支持时间桶与 tag)。返回 `None` 表示放行,`Some(feature)`
/// 为统一的拒绝文案。
#[cfg(any(feature = "clickhouse", feature = "influxdb"))]
pub(crate) fn clickhouse_projection_gate(
    db_type: super::super::DbType,
) -> Option<&'static str> {
    if Capabilities::of(db_type).advanced_grouping {
        return None;
    }
    // DbType::InfluxDB 变体仅在 influxdb feature 下存在,需同步门控。
    #[cfg(feature = "influxdb")]
    if db_type == super::super::DbType::InfluxDB {
        return Some(
            "GROUP BY aggregation on InfluxDB (InfluxQL GROUP BY only supports time buckets and tags)",
        );
    }
    Some("GROUP BY aggregation")
}

pub trait NestedInclude<'a, Owner: Model>: Clone {
    fn load_nested_include<'b>(
        self,
        executor: &'b SelectExecutor<'a, Owner>,
        owners: &'b mut [Owner],
    ) -> Pin<Box<dyn Future<Output = crate::Result<()>> + Send + 'b>>
    where
        Owner: 'static + Send + Sync,
        'a: 'b;
}

impl<'a, Owner: Model> NestedInclude<'a, Owner> for NoInclude {
    fn load_nested_include<'b>(
        self,
        _executor: &'b SelectExecutor<'a, Owner>,
        _owners: &'b mut [Owner],
    ) -> Pin<Box<dyn Future<Output = crate::Result<()>> + Send + 'b>>
    where
        Owner: 'static + Send + Sync,
        'a: 'b,
    {
        Box::pin(async { Ok(()) })
    }
}

impl<'a, Owner, Target> NestedInclude<'a, Owner> for Relation<Owner, Target>
where
    Owner: Model + 'static + Send + Sync,
    Target: Model + Clone + 'static + Send + Sync,
{
    fn load_nested_include<'b>(
        self,
        executor: &'b SelectExecutor<'a, Owner>,
        owners: &'b mut [Owner],
    ) -> Pin<Box<dyn Future<Output = crate::Result<()>> + Send + 'b>>
    where
        Owner: 'static + Send + Sync,
        'a: 'b,
    {
        Box::pin(async move { executor.preload_models_with_selection(owners, self).await })
    }
}

impl<'a, Owner, Via, Target> NestedInclude<'a, Owner> for ThroughRelation<Owner, Via, Target>
where
    Owner: Model + 'static + Send + Sync,
    Via: Model + Clone + 'static + Send + Sync,
    Target: Model + Clone + 'static + Send + Sync,
{
    fn load_nested_include<'b>(
        self,
        executor: &'b SelectExecutor<'a, Owner>,
        owners: &'b mut [Owner],
    ) -> Pin<Box<dyn Future<Output = crate::Result<()>> + Send + 'b>>
    where
        Owner: 'static + Send + Sync,
        'a: 'b,
    {
        Box::pin(async move { executor.preload_models_with_selection(owners, self).await })
    }
}

impl<'a, Owner, Target, Handle, Nested> NestedInclude<'a, Owner>
    for RelationQuery<Owner, Target, Handle, Nested>
where
    Owner: Model + 'static + Send + Sync,
    Target: Model + Clone + 'static + Send + Sync,
    Handle: RelationHandle<Owner, Target> + Clone + Send + Sync + 'static,
    Handle::Via: Send + Sync,
    Nested: NestedInclude<'a, Target> + Clone + Send + Sync + 'static,
{
    fn load_nested_include<'b>(
        self,
        executor: &'b SelectExecutor<'a, Owner>,
        owners: &'b mut [Owner],
    ) -> Pin<Box<dyn Future<Output = crate::Result<()>> + Send + 'b>>
    where
        Owner: 'static + Send + Sync,
        'a: 'b,
    {
        Box::pin(async move { executor.preload_models_with_selection(owners, self).await })
    }
}

pub trait RelationNestedLoader<'a, Owner: Model>: RelationSelection<Owner> {
    fn load_nested<'b>(
        &'b self,
        executor: &'b SelectExecutor<'a, Self::Target>,
        related: &'b mut [Self::Target],
    ) -> Pin<Box<dyn Future<Output = crate::Result<()>> + Send + 'b>>
    where
        Owner: 'static + Send + Sync,
        Self::Target: Send + Sync,
        'a: 'b;
}

impl<'a, Owner, Target> RelationNestedLoader<'a, Owner> for Relation<Owner, Target>
where
    Owner: Model + 'static + Send + Sync,
    Target: Model + Clone + 'static + Send + Sync,
{
    fn load_nested<'b>(
        &'b self,
        _executor: &'b SelectExecutor<'a, Self::Target>,
        _related: &'b mut [Self::Target],
    ) -> Pin<Box<dyn Future<Output = crate::Result<()>> + Send + 'b>>
    where
        Owner: 'static + Send + Sync,
        Self::Target: Send + Sync,
        'a: 'b,
    {
        Box::pin(async { Ok(()) })
    }
}

impl<'a, Owner, Via, Target> RelationNestedLoader<'a, Owner> for ThroughRelation<Owner, Via, Target>
where
    Owner: Model + 'static + Send + Sync,
    Via: Model + Clone + 'static + Send + Sync,
    Target: Model + Clone + 'static + Send + Sync,
{
    fn load_nested<'b>(
        &'b self,
        _executor: &'b SelectExecutor<'a, Self::Target>,
        _related: &'b mut [Self::Target],
    ) -> Pin<Box<dyn Future<Output = crate::Result<()>> + Send + 'b>>
    where
        Owner: 'static + Send + Sync,
        Self::Target: Send + Sync,
        'a: 'b,
    {
        Box::pin(async { Ok(()) })
    }
}

impl<'a, Owner, Target, Handle, Nested> RelationNestedLoader<'a, Owner>
    for RelationQuery<Owner, Target, Handle, Nested>
where
    Owner: Model + 'static + Send + Sync,
    Target: Model + Clone + 'static + Send + Sync,
    Handle: RelationHandle<Owner, Target> + Clone + Send + Sync + 'static,
    Handle::Via: Send + Sync,
    Nested: NestedInclude<'a, Target> + Clone + Send + Sync + 'static,
{
    fn load_nested<'b>(
        &'b self,
        executor: &'b SelectExecutor<'a, Self::Target>,
        related: &'b mut [Self::Target],
    ) -> Pin<Box<dyn Future<Output = crate::Result<()>> + Send + 'b>>
    where
        Owner: 'static + Send + Sync,
        Self::Target: Send + Sync,
        'a: 'b,
    {
        let nested = self.nested().clone();
        Box::pin(async move { nested.load_nested_include(executor, related).await })
    }
}

/// 统一的 Database 枚举
pub enum Database {
    #[cfg(feature = "sqlite")]
    Sqlite(sqlite_backend::Database),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::Database),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::Database),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::Database),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::Database),
    #[cfg(feature = "clickhouse")]
    ClickHouse(super::super::clickhouse_backend::Database),
    #[cfg(feature = "influxdb")]
    InfluxDB(super::super::influxdb_backend::Database),
}

pub struct ReplicatedDatabaseBuilder {
    db_type: super::super::DbType,
    write_connection: Option<String>,
    read_connections: Vec<String>,
}

pub struct ReplicatedDatabase {
    db_type: super::super::DbType,
    write: Database,
    reads: Vec<Database>,
    next_read: AtomicUsize,
}

impl ReplicatedDatabaseBuilder {
    pub(crate) fn new(db_type: super::super::DbType) -> Self {
        Self {
            db_type,
            write_connection: None,
            read_connections: Vec::new(),
        }
    }

    pub fn write(mut self, connection_string: impl Into<String>) -> Self {
        self.write_connection = Some(connection_string.into());
        self
    }

    pub fn read(mut self, connection_string: impl Into<String>) -> Self {
        self.read_connections.push(connection_string.into());
        self
    }

    pub async fn connect(self) -> crate::Result<ReplicatedDatabase> {
        let Some(write_connection) = self.write_connection else {
            return Err(crate::ormer_error!(
                "replicated database requires a write connection"
            ));
        };

        let write = Database::connect(self.db_type, &write_connection).await?;
        let mut reads = Vec::with_capacity(self.read_connections.len());
        for connection in self.read_connections {
            reads.push(Database::connect(self.db_type, &connection).await?);
        }

        Ok(ReplicatedDatabase {
            db_type: self.db_type,
            write,
            reads,
            next_read: AtomicUsize::new(0),
        })
    }
}

impl ReplicatedDatabase {
    pub fn db_type(&self) -> super::super::DbType {
        self.db_type
    }

    pub fn sql_trace(&self) -> crate::SqlTraceBuilder {
        crate::global_sql_trace().builder()
    }

    pub fn write(&self) -> &Database {
        &self.write
    }

    pub fn read(&self) -> &Database {
        if self.reads.is_empty() {
            return &self.write;
        }
        let index = self.next_read.fetch_add(1, Ordering::Relaxed) % self.reads.len();
        &self.reads[index]
    }

    pub fn scope(&self) -> DatabaseScope<'_> {
        self.write().scope()
    }

    pub async fn transaction<R, F>(&self, f: F) -> crate::Result<R>
    where
        F: for<'tx> FnOnce(&'tx mut Transaction<'_>) -> TransactionFuture<'tx, R>,
    {
        self.write.transaction(f).await
    }

    pub async fn transaction_opts<R, F>(
        &self,
        options: TransactionOptions,
        f: F,
    ) -> crate::Result<R>
    where
        F: for<'tx> FnOnce(&'tx mut Transaction<'_>) -> TransactionFuture<'tx, R>,
    {
        self.write.transaction_opts(options, f).await
    }
}

pub struct DerivedTableSelectExecutor<'a, R: Model> {
    db: &'a Database,
    select: DerivedTableSelect<R>,
}

#[derive(Clone)]
pub struct DatabaseScope<'a> {
    db: &'a Database,
    context_filters: Vec<ContextFilter>,
}

impl<'a> DatabaseScope<'a> {
    pub fn select<T: Model>(&self) -> SelectExecutor<'a, T> {
        self.db
            .select::<T>()
            .with_context_filters(self.context_filters.clone())
    }

    pub async fn find_by_id<T: Model + 'static + Send + Sync>(
        &self,
        key: impl crate::model::PrimaryKey,
    ) -> crate::Result<Option<T>> {
        find_by_id_with_executor(self.select::<T>(), key).await
    }

    pub async fn find_related<T, S>(
        &self,
        owner: &T,
        relation: S,
    ) -> crate::Result<Vec<S::Target>>
    where
        T: Model + 'static + Send + Sync,
        S: RelationSelection<T>,
        for<'b> S: RelationNestedLoader<'b, T> + Send + Sync,
        S::Target: Send + Sync,
        S::Via: Send + Sync,
    {
        find_related_with_executor(&self.select::<T>(), owner, &relation).await
    }

    pub async fn preload<T, S>(
        &self,
        owners: &mut [T],
        relation: S,
    ) -> crate::Result<()>
    where
        T: Model + 'static + Send + Sync,
        S: RelationSelection<T>,
        for<'b> S: RelationNestedLoader<'b, T> + Send + Sync,
        S::Target: Send + Sync,
        S::Via: Send + Sync,
    {
        preload_with_executor(&self.select::<T>(), owners, relation).await
    }

    pub fn delete<T: WritableModel>(&self) -> ScopedDeleteExecutor<'a, T> {
        ScopedDeleteExecutor {
            inner: self.db.delete::<T>(),
            context_filters: self.context_filters.clone(),
            disabled_filters: Vec::new(),
        }
    }

    pub fn update<T: WritableModel>(&self) -> ScopedUpdateExecutor<'a, T> {
        ScopedUpdateExecutor {
            inner: self.db.update::<T>(),
            context_filters: self.context_filters.clone(),
            disabled_filters: Vec::new(),
        }
    }
}

#[cfg(feature = "clickhouse")]
async fn clickhouse_select_models<T, C>(
    db: &super::super::clickhouse_backend::Database,
    select: Select<T>,
) -> crate::Result<C>
where
    T: Model,
    C: FromIterator<T>,
{
    let (sql, params) = select.try_to_sql_with_params(super::super::DbType::ClickHouse)?;
    let columns = T::columns();
    let rows = db
        .select_values(RawSql::new(sql).with_params(params), Some(&columns))
        .await?;
    rows.iter()
        .map(|values| T::from_row_values(values))
        .collect()
}

/// 渲染 InfluxQL 并解析结果为模型集合(与 ClickHouse 路径共用统一查询构建器)。
#[cfg(feature = "influxdb")]
async fn influx_select_models<T, C>(
    db: &influxdb_backend::Database,
    select: Select<T>,
) -> crate::Result<C>
where
    T: Model,
    C: FromIterator<T>,
{
    let (sql, params) = select.try_to_sql_with_params(super::super::DbType::InfluxDB)?;
    let columns = T::columns();
    let rows = db
        .select_values(RawSql::new(sql).with_params(params), Some(&columns))
        .await?;
    rows.iter()
        .map(|values| T::from_row_values(values))
        .collect()
}

/// 在 ClickHouse 协议后端上执行聚合 SELECT,返回单列聚合值。
///
/// InfluxQL 没有 `AVG`,对应语义是 `MEAN`,在此按前缀替换;
/// COUNT/SUM/MIN/MAX 两边语法一致。
#[cfg(any(feature = "clickhouse", feature = "influxdb"))]
async fn clickhouse_aggregate_on_backend<T, R>(
    db: ClickHouseSelectBackend<'_>,
    aggregate: crate::query::builder::AggregateSelect<T, R>,
) -> crate::Result<R>
where
    T: Model,
    R: crate::model::FromValue,
{
    let backend = clickhouse_select_backend_db_type(db);
    // InfluxQL 没有 AVG,对应语义是 MEAN(仅 influxdb 构建需要改写 sql)
    #[cfg_attr(not(feature = "influxdb"), allow(unused_mut))]
    let (mut sql, params) = aggregate.try_to_sql_with_params(backend)?;
    #[cfg(feature = "influxdb")]
    if backend == super::super::DbType::InfluxDB && sql.starts_with("SELECT AVG(") {
        sql = sql.replacen("SELECT AVG(", "SELECT MEAN(", 1);
    }
    let rows = match db {
        #[cfg(feature = "clickhouse")]
        ClickHouseSelectBackend::ClickHouse(db) => {
            db.select_values(RawSql::new(sql).with_params(params), None).await?
        }
        #[cfg(feature = "influxdb")]
        ClickHouseSelectBackend::Influx(db) => {
            db.raw_select_values(RawSql::new(sql).with_params(params), None).await?
        }
    };
    let value = rows
        .first()
        .and_then(|row| row.first().cloned())
        .unwrap_or(Value::Null);
    R::from_value(&value)
}

#[cfg(any(feature = "clickhouse", feature = "influxdb"))]
async fn clickhouse_select_models_on_backend<T, C>(
    db: ClickHouseSelectBackend<'_>,
    select: Select<T>,
) -> crate::Result<C>
where
    T: Model,
    C: FromIterator<T>,
{
    match db {
        #[cfg(feature = "clickhouse")]
        ClickHouseSelectBackend::ClickHouse(db) => {
            clickhouse_select_models::<T, C>(db, select).await
        }
        #[cfg(feature = "influxdb")]
        ClickHouseSelectBackend::Influx(db) => influx_select_models::<T, C>(db, select).await,
    }
}

#[cfg(any(feature = "clickhouse", feature = "influxdb"))]
async fn clickhouse_select_first_on_backend<T>(
    db: ClickHouseSelectBackend<'_>,
    select: Select<T>,
) -> crate::Result<Option<T>>
where
    T: Model + Send + Sync,
{
    Ok(
        clickhouse_select_models_on_backend::<T, Vec<T>>(db, select)
            .await?
            .into_iter()
            .next(),
    )
}

#[cfg(any(feature = "clickhouse", feature = "influxdb"))]
async fn clickhouse_fetch_page_on_backend<T>(
    db: ClickHouseSelectBackend<'_>,
    select: Select<T>,
) -> crate::Result<crate::query::builder::CursorPage<T>>
where
    T: Model + Send + Sync,
{
    let (select, cursor_columns) = select.prepare_cursor_page()?;
    let items =
        clickhouse_select_models_on_backend::<T, Vec<T>>(db, select.clone()).await?;
    select.finish_cursor_page(items, &cursor_columns)
}

impl<'a, T: Model> NamedFilterQuery<T> for DatabaseScope<'a> {
    fn apply_named_filter(mut self, name: &'static str, expr: WhereExpr) -> Self {
        self.context_filters
            .push(ContextFilter::new::<T>(name, expr));
        self
    }
}

/// 统一的 CreateTableExecutor 枚举
pub enum CreateTableExecutor<'a, T: crate::model::WritableModel> {
    #[cfg(feature = "sqlite")]
    Sqlite(sqlite_backend::CreateTableExecutor<'a, T>),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::CreateTableExecutor<'a, T>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::CreateTableExecutor<'a, T>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::CreateTableExecutor<'a, T>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::CreateTableExecutor<'a, T>),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        _marker: std::marker::PhantomData<&'a T>,
    },
    #[cfg(feature = "influxdb")]
    InfluxDB(
        &'a influxdb_backend::Database,
        std::marker::PhantomData<&'a T>,
    ),
}

impl<'a, T: crate::model::WritableModel> CreateTableExecutor<'a, T> {
    // table_name 仅由本地后端分支消费(InfluxDB measurement 名称由模型固定)
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb"
        )),
        allow(unused_variables)
    )]
    pub fn with_table_name(self, table_name: &str) -> Self {
        match self {
            #[cfg(feature = "sqlite")]
            CreateTableExecutor::Sqlite(exec) => {
                CreateTableExecutor::Sqlite(exec.with_table_name(table_name))
            }
            #[cfg(feature = "postgresql")]
            CreateTableExecutor::PostgreSQL(exec) => {
                CreateTableExecutor::PostgreSQL(exec.with_table_name(table_name))
            }
            #[cfg(feature = "mysql")]
            CreateTableExecutor::MySQL(exec) => {
                CreateTableExecutor::MySQL(exec.with_table_name(table_name))
            }
            #[cfg(feature = "mssql")]
            CreateTableExecutor::MSSQL(exec) => {
                CreateTableExecutor::MSSQL(exec.with_table_name(table_name))
            }
            #[cfg(feature = "duckdb")]
            CreateTableExecutor::DuckDB(exec) => {
                CreateTableExecutor::DuckDB(exec.with_table_name(table_name))
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            unsupported @ CreateTableExecutor::Unsupported { .. } => unsupported,
            // InfluxDB measurement 名称由模型固定,表路由不生效
            #[cfg(feature = "influxdb")]
            unsupported @ CreateTableExecutor::InfluxDB(..) => unsupported,
        }
    }

    /// 标记为路由子表建表:PostgreSQL 的 DDL 序列尾部追加 TimescaleDB 列存
    /// 压缩与自动压缩策略;表路由本就是 PG 专属能力,其余后端原样返回。
    pub fn with_route_columnstore(self) -> Self {
        match self {
            #[cfg(feature = "postgresql")]
            CreateTableExecutor::PostgreSQL(exec) => {
                CreateTableExecutor::PostgreSQL(exec.with_route_columnstore())
            }
            // 仅启用 postgresql feature 时其余变体不存在,兜底臂不可达
            #[allow(unreachable_patterns)]
            other => other,
        }
    }

    pub fn route_table(self, key: impl Into<String>, value: impl TableRouteValue) -> Self {
        let mut route = crate::model::TableRoute::new();
        route.insert(key, value);
        self.with_table_route(route)
    }

    pub fn with_table_route(self, route: crate::model::TableRoute) -> Self {
        let db_type = match &self {
            #[cfg(feature = "sqlite")]
            CreateTableExecutor::Sqlite(_) => crate::abstract_layer::DbType::Sqlite,
            #[cfg(feature = "postgresql")]
            CreateTableExecutor::PostgreSQL(_) => crate::abstract_layer::DbType::PostgreSQL,
            #[cfg(feature = "mysql")]
            CreateTableExecutor::MySQL(_) => crate::abstract_layer::DbType::MySQL,
            #[cfg(feature = "mssql")]
            CreateTableExecutor::MSSQL(_) => crate::abstract_layer::DbType::MSSQL,
            #[cfg(feature = "duckdb")]
            CreateTableExecutor::DuckDB(_) => crate::abstract_layer::DbType::DuckDB,
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            CreateTableExecutor::Unsupported { backend, .. } => *backend,
            #[cfg(feature = "influxdb")]
            CreateTableExecutor::InfluxDB(..) => super::super::DbType::InfluxDB,
        };
        let table_name = routed_model_table_name_for_db::<T>(db_type, &route)
            .unwrap_or_else(|err| panic!("Failed to render table route: {}", err));
        self.with_table_name(&table_name)
    }

    pub fn to_sql(&self) -> crate::Result<SqlStatement> {
        match self {
            #[cfg(feature = "sqlite")]
            CreateTableExecutor::Sqlite(exec) => exec.to_sql(),
            #[cfg(feature = "postgresql")]
            CreateTableExecutor::PostgreSQL(exec) => exec.to_sql(),
            #[cfg(feature = "mysql")]
            CreateTableExecutor::MySQL(exec) => exec.to_sql(),
            #[cfg(feature = "mssql")]
            CreateTableExecutor::MSSQL(exec) => exec.to_sql(),
            #[cfg(feature = "duckdb")]
            CreateTableExecutor::DuckDB(exec) => exec.to_sql(),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            CreateTableExecutor::Unsupported {
                backend, feature, ..
            } => Err(unsupported_feature(*backend, feature)),
            #[cfg(feature = "influxdb")]
            CreateTableExecutor::InfluxDB(..) => Err(unsupported_feature(
                super::super::DbType::InfluxDB,
                "create_table to_sql (retention policy is applied over HTTP)",
            )),
        }
    }

    pub async fn execute(self) -> crate::Result<()> {
        match self {
            #[cfg(feature = "sqlite")]
            CreateTableExecutor::Sqlite(exec) => exec.execute().await,
            #[cfg(feature = "postgresql")]
            CreateTableExecutor::PostgreSQL(exec) => exec.execute().await,
            #[cfg(feature = "mysql")]
            CreateTableExecutor::MySQL(exec) => exec.execute().await,
            #[cfg(feature = "mssql")]
            CreateTableExecutor::MSSQL(exec) => exec.execute().await,
            #[cfg(feature = "duckdb")]
            CreateTableExecutor::DuckDB(exec) => exec.execute().await,
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            CreateTableExecutor::Unsupported {
                backend, feature, ..
            } => Err(unsupported_feature(backend, feature)),
            #[cfg(feature = "influxdb")]
            CreateTableExecutor::InfluxDB(db, _) => db.create_table::<T>().await,
        }?;
        crate::model::clear_version_snapshots::<T>();
        Ok(())
    }
}

/// 统一的 DropTableExecutor 枚举
pub enum DropTableExecutor<'a, T: crate::model::WritableModel> {
    #[cfg(feature = "sqlite")]
    Sqlite(sqlite_backend::DropTableExecutor<'a, T>),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::DropTableExecutor<'a, T>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::DropTableExecutor<'a, T>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::DropTableExecutor<'a, T>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::DropTableExecutor<'a, T>),
    #[cfg(feature = "clickhouse")]
    ClickHouse(
        &'a super::super::clickhouse_backend::Database,
        std::marker::PhantomData<T>,
    ),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        _marker: std::marker::PhantomData<&'a T>,
    },
    #[cfg(feature = "influxdb")]
    InfluxDB(
        &'a influxdb_backend::Database,
        std::marker::PhantomData<&'a T>,
    ),
}

impl<'a, T: crate::model::WritableModel> DropTableExecutor<'a, T> {
    /// 设置拆表路由键值(渲染 `{表名}_{路由值}` 子表名)。
    // route 仅由 PostgreSQL 变体消费(其余后端落基础表名)
    #[allow(unused_variables)]
    pub fn route_table(
        self,
        key: impl Into<String>,
        value: impl crate::model::TableRouteValue,
    ) -> Self {
        let mut route = crate::model::TableRoute::new();
        route.insert(key, value);
        self.with_table_route(route)
    }

    /// 合并拆表路由(已有同名字段值不被覆盖)。
    // route 仅由 PostgreSQL 变体消费(其余后端落基础表名)
    #[allow(unused_variables)]
    pub fn with_table_route(self, route: crate::model::TableRoute) -> Self {
        match self {
            // route key 仅 PostgreSQL/表名模板语义,此后端忽略
            #[cfg(feature = "sqlite")]
            this @ DropTableExecutor::Sqlite(..) => this,
            #[cfg(feature = "postgresql")]
            DropTableExecutor::PostgreSQL(exec) => {
                DropTableExecutor::PostgreSQL(exec.with_table_route(route))
            }
            // route key 仅 PostgreSQL/表名模板语义,此后端忽略
            #[cfg(feature = "mysql")]
            this @ DropTableExecutor::MySQL(..) => this,
            // route key 仅 PostgreSQL/表名模板语义,此后端忽略
            #[cfg(feature = "mssql")]
            this @ DropTableExecutor::MSSQL(..) => this,
            // route key 仅 PostgreSQL/表名模板语义,此后端忽略
            #[cfg(feature = "duckdb")]
            this @ DropTableExecutor::DuckDB(..) => this,
            // route key 仅 PostgreSQL/表名模板语义,此后端忽略
            #[cfg(feature = "clickhouse")]
            this @ DropTableExecutor::ClickHouse(..) => this,
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            unsupported @ DropTableExecutor::Unsupported { .. } => unsupported,
            // route key 仅 PostgreSQL/表名模板语义,此后端忽略
            #[cfg(feature = "influxdb")]
            this @ DropTableExecutor::InfluxDB(..) => this,
        }
    }

    pub fn to_sql(&self) -> crate::Result<SqlStatement> {
        match self {
            #[cfg(feature = "sqlite")]
            DropTableExecutor::Sqlite(exec) => exec.to_sql(),
            #[cfg(feature = "postgresql")]
            DropTableExecutor::PostgreSQL(exec) => exec.to_sql(),
            #[cfg(feature = "mysql")]
            DropTableExecutor::MySQL(exec) => exec.to_sql(),
            #[cfg(feature = "mssql")]
            DropTableExecutor::MSSQL(exec) => exec.to_sql(),
            #[cfg(feature = "duckdb")]
            DropTableExecutor::DuckDB(exec) => exec.to_sql(),
            #[cfg(feature = "clickhouse")]
            DropTableExecutor::ClickHouse(_, _) => {
                let table = crate::model::quote_qualified_identifier(
                    super::super::DbType::ClickHouse,
                    T::table_name_for_db(super::super::DbType::ClickHouse),
                );
                Ok(SqlStatement::single(
                    super::super::DbType::ClickHouse,
                    format!("DROP TABLE IF EXISTS {table}"),
                    Vec::new(),
                ))
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            DropTableExecutor::Unsupported {
                backend, feature, ..
            } => Err(unsupported_feature(*backend, feature)),
            #[cfg(feature = "influxdb")]
            DropTableExecutor::InfluxDB(..) => {
                let table = crate::model::quote_qualified_identifier(
                    super::super::DbType::InfluxDB,
                    T::table_name_for_db(super::super::DbType::InfluxDB),
                );
                Ok(SqlStatement::single(
                    super::super::DbType::InfluxDB,
                    format!("DROP MEASUREMENT {table}"),
                    Vec::new(),
                ))
            }
        }
    }

    pub async fn execute(self) -> crate::Result<()> {
        match self {
            #[cfg(feature = "sqlite")]
            DropTableExecutor::Sqlite(exec) => exec.execute().await,
            #[cfg(feature = "postgresql")]
            DropTableExecutor::PostgreSQL(exec) => exec.execute().await,
            #[cfg(feature = "mysql")]
            DropTableExecutor::MySQL(exec) => exec.execute().await,
            #[cfg(feature = "mssql")]
            DropTableExecutor::MSSQL(exec) => exec.execute().await,
            #[cfg(feature = "duckdb")]
            DropTableExecutor::DuckDB(exec) => exec.execute().await,
            #[cfg(feature = "clickhouse")]
            DropTableExecutor::ClickHouse(db, _) => db.drop_table::<T>().await,
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            DropTableExecutor::Unsupported {
                backend, feature, ..
            } => Err(unsupported_feature(backend, feature)),
            #[cfg(feature = "influxdb")]
            DropTableExecutor::InfluxDB(db, _) => db.drop_table::<T>().await,
        }?;
        crate::model::clear_version_snapshots::<T>();
        Ok(())
    }
}

/// 统一的 TruncateTableExecutor 枚举:`TRUNCATE TABLE t`。
///
/// QuestDB 不支持行级 DELETE,`truncate_table` 是唯一的清空表数据手段;
/// PostgreSQL/MySQL/MSSQL/DuckDB 同样原生支持;SQLite 无 TRUNCATE 语法
/// (能力矩阵为 false),ClickHouse/InfluxDB 未接入执行器。
pub enum TruncateTableExecutor<'a, T: crate::model::WritableModel> {
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::TruncateTableExecutor<'a, T>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::TruncateTableExecutor<'a, T>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::TruncateTableExecutor<'a, T>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::TruncateTableExecutor<'a, T>),
    /// 能力矩阵门控产物:`truncate: false` 的后端在
    /// [`Database::truncate_table`] 构造时落入该变体。
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        _marker: std::marker::PhantomData<&'a T>,
    },
}

impl<'a, T: crate::model::WritableModel> TruncateTableExecutor<'a, T> {
    /// 设置拆表路由键值(渲染 `{表名}_{路由值}` 子表名)。
    // route 仅由 PostgreSQL 变体消费(其余后端落基础表名)
    #[allow(unused_variables)]
    pub fn route_table(
        self,
        key: impl Into<String>,
        value: impl crate::model::TableRouteValue,
    ) -> Self {
        let mut route = crate::model::TableRoute::new();
        route.insert(key, value);
        self.with_table_route(route)
    }

    /// 合并拆表路由(已有同名字段值不被覆盖)。
    // route 仅由 PostgreSQL 变体消费(其余后端落基础表名)
    #[allow(unused_variables)]
    pub fn with_table_route(self, route: crate::model::TableRoute) -> Self {
        match self {
            #[cfg(feature = "postgresql")]
            TruncateTableExecutor::PostgreSQL(exec) => {
                TruncateTableExecutor::PostgreSQL(exec.with_table_route(route))
            }
            // route key 仅 PostgreSQL/表名模板语义,此后端忽略
            #[cfg(feature = "mysql")]
            this @ TruncateTableExecutor::MySQL(..) => this,
            // route key 仅 PostgreSQL/表名模板语义,此后端忽略
            #[cfg(feature = "mssql")]
            this @ TruncateTableExecutor::MSSQL(..) => this,
            // route key 仅 PostgreSQL/表名模板语义,此后端忽略
            #[cfg(feature = "duckdb")]
            this @ TruncateTableExecutor::DuckDB(..) => this,
            unsupported @ TruncateTableExecutor::Unsupported { .. } => unsupported,
        }
    }

    pub fn to_sql(&self) -> crate::Result<SqlStatement> {
        match self {
            #[cfg(feature = "postgresql")]
            TruncateTableExecutor::PostgreSQL(exec) => exec.to_sql(),
            #[cfg(feature = "mysql")]
            TruncateTableExecutor::MySQL(exec) => exec.to_sql(),
            #[cfg(feature = "mssql")]
            TruncateTableExecutor::MSSQL(exec) => exec.to_sql(),
            #[cfg(feature = "duckdb")]
            TruncateTableExecutor::DuckDB(exec) => exec.to_sql(),
            TruncateTableExecutor::Unsupported {
                backend, feature, ..
            } => Err(unsupported_feature(*backend, feature)),
        }
    }

    pub async fn execute(self) -> crate::Result<()> {
        match self {
            #[cfg(feature = "postgresql")]
            TruncateTableExecutor::PostgreSQL(exec) => exec.execute().await,
            #[cfg(feature = "mysql")]
            TruncateTableExecutor::MySQL(exec) => exec.execute().await,
            #[cfg(feature = "mssql")]
            TruncateTableExecutor::MSSQL(exec) => exec.execute().await,
            #[cfg(feature = "duckdb")]
            TruncateTableExecutor::DuckDB(exec) => exec.execute().await,
            TruncateTableExecutor::Unsupported {
                backend, feature, ..
            } => Err(unsupported_feature(backend, feature)),
        }?;
        crate::model::clear_version_snapshots::<T>();
        Ok(())
    }
}

/// 统一的 InsertExecutor 枚举
pub enum InsertExecutor<'a, I: crate::model::Insertable> {
    #[cfg(feature = "sqlite")]
    Sqlite(sqlite_backend::InsertExecutor<'a, I>),
    #[cfg(feature = "sqlite")]
    /// 事务路径变体:持有后端事务插入执行器,与 `Sqlite` 变体共享同一套
    /// 链式配置方法(原 `TransactionInsertExecutor` 已合并入本枚举)。
    SqliteTxn(sqlite_backend::TransactionInsertExecutor<'a, I>),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::InsertExecutor<'a, I>),
    #[cfg(feature = "postgresql")]
    /// 事务路径变体(原 `TransactionInsertExecutor` 的 PostgreSQL 分支)。
    PostgreSQLTxn(postgresql_backend::TransactionInsertExecutor<'a, I>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::InsertExecutor<'a, I>),
    #[cfg(feature = "mysql")]
    /// 事务路径变体(原 `TransactionInsertExecutor` 的 MySQL 分支)。
    MySQLTxn(mysql_backend::TransactionInsertExecutor<'a, I>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::InsertExecutor<'a, I>),
    #[cfg(feature = "mssql")]
    /// 事务路径变体(原 `TransactionInsertExecutor` 的 MSSQL 分支)。
    MSSQLTxn(mssql_backend::TransactionInsertExecutor<'a, I>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::InsertExecutor<'a, I>),
    #[cfg(feature = "duckdb")]
    /// 事务路径变体(原 `TransactionInsertExecutor` 的 DuckDB 分支)。
    DuckDBTxn(duckdb_backend::TransactionInsertExecutor<'a, I>),
    #[cfg(feature = "clickhouse")]
    ClickHouse(
        &'a clickhouse_backend::Database,
        I,
        Option<crate::query::insert::InsertConflict>,
        std::marker::PhantomData<I::Model>,
    ),
    #[cfg(feature = "influxdb")]
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        models: I,
        _marker: std::marker::PhantomData<I::Model>,
        _lifetime: std::marker::PhantomData<&'a ()>,
    },
    #[cfg(feature = "influxdb")]
    InfluxDB(
        &'a influxdb_backend::Database,
        I,
        Option<crate::query::insert::InsertConflict>,
        std::marker::PhantomData<I::Model>,
    ),
}

/// 旧事务插入执行器名过渡别名(已合并为 [`InsertExecutor`],保留
/// re-export 以兼容现有导入路径;事务入口 [`Transaction::insert`]
/// 返回的就是 [`InsertExecutor`] 的事务变体)。
#[deprecated(
    since = "0.2.12",
    note = "TransactionInsertExecutor 已合并为 InsertExecutor,请改用 InsertExecutor"
)]
pub type TransactionInsertExecutor<'a, I> = InsertExecutor<'a, I>;

pub enum InsertPartialExecutor<'a, T: Model> {
    #[cfg(feature = "sqlite")]
    Sqlite(
        sqlite_backend::InsertPartialExecutor<'a, T>,
        std::marker::PhantomData<&'a T>,
    ),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::InsertPartialExecutor<'a, T>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::InsertPartialExecutor<'a, T>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::InsertPartialExecutor<'a, T>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::InsertPartialExecutor<'a, T>),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        _marker: std::marker::PhantomData<&'a T>,
    },
}

impl<'a, T: Model> InsertPartialExecutor<'a, T> {
    /// 设置拆表路由键值(渲染 `{表名}_{路由值}` 子表名)。
    // route 仅由本地后端分支消费(ClickHouse/InfluxDB 不支持 partial insert)
    #[allow(unused_variables)]
    pub fn route_table(
        self,
        key: impl Into<String>,
        value: impl crate::model::TableRouteValue,
    ) -> Self {
        let mut route = crate::model::TableRoute::new();
        route.insert(key, value);
        self.with_table_route(route)
    }

    /// 合并拆表路由(已有同名字段值不被覆盖)。
    // route 仅由本地后端分支消费(ClickHouse/InfluxDB 不支持 partial insert)
    #[allow(unused_variables)]
    pub fn with_table_route(self, route: crate::model::TableRoute) -> Self {
        match self {
            #[cfg(feature = "sqlite")]
            InsertPartialExecutor::Sqlite(exec, phantom) => {
                InsertPartialExecutor::Sqlite(exec.with_table_route(route), phantom)
            }
            #[cfg(feature = "postgresql")]
            InsertPartialExecutor::PostgreSQL(exec) => {
                InsertPartialExecutor::PostgreSQL(exec.with_table_route(route))
            }
            #[cfg(feature = "mysql")]
            InsertPartialExecutor::MySQL(exec) => {
                InsertPartialExecutor::MySQL(exec.with_table_route(route))
            }
            #[cfg(feature = "mssql")]
            InsertPartialExecutor::MSSQL(exec) => {
                InsertPartialExecutor::MSSQL(exec.with_table_route(route))
            }
            #[cfg(feature = "duckdb")]
            InsertPartialExecutor::DuckDB(exec) => {
                InsertPartialExecutor::DuckDB(exec.with_table_route(route))
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            unsupported @ InsertPartialExecutor::Unsupported { .. } => unsupported,
        }
    }
}

impl<'a, T: Model + Send + Sync> InsertPartialExecutor<'a, T> {
    // f 仅由本地后端分支消费(ClickHouse/InfluxDB 不支持 partial insert)
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb"
        )),
        allow(unused_variables)
    )]
    pub fn set<F, A>(self, f: F) -> Self
    where
        F: FnOnce(T::Where) -> A,
        A: IntoInsertAssignment<T>,
    {
        match self {
            #[cfg(feature = "sqlite")]
            InsertPartialExecutor::Sqlite(exec, phantom) => {
                InsertPartialExecutor::Sqlite(exec.set(f), phantom)
            }
            #[cfg(feature = "postgresql")]
            InsertPartialExecutor::PostgreSQL(exec) => {
                InsertPartialExecutor::PostgreSQL(exec.set(f))
            }
            #[cfg(feature = "mysql")]
            InsertPartialExecutor::MySQL(exec) => InsertPartialExecutor::MySQL(exec.set(f)),
            #[cfg(feature = "mssql")]
            InsertPartialExecutor::MSSQL(exec) => InsertPartialExecutor::MSSQL(exec.set(f)),
            #[cfg(feature = "duckdb")]
            InsertPartialExecutor::DuckDB(exec) => InsertPartialExecutor::DuckDB(exec.set(f)),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            unsupported @ InsertPartialExecutor::Unsupported { .. } => unsupported,
        }
    }

    // f 仅由本地后端分支消费(ClickHouse/InfluxDB 不支持 partial insert)
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb"
        )),
        allow(unused_variables)
    )]
    pub fn default<F, C>(self, f: F) -> Self
    where
        F: FnOnce(T::Where) -> C,
        C: IntoInsertDefaultColumn<T>,
    {
        match self {
            #[cfg(feature = "sqlite")]
            InsertPartialExecutor::Sqlite(exec, phantom) => {
                InsertPartialExecutor::Sqlite(exec.default(f), phantom)
            }
            #[cfg(feature = "postgresql")]
            InsertPartialExecutor::PostgreSQL(exec) => {
                InsertPartialExecutor::PostgreSQL(exec.default(f))
            }
            #[cfg(feature = "mysql")]
            InsertPartialExecutor::MySQL(exec) => InsertPartialExecutor::MySQL(exec.default(f)),
            #[cfg(feature = "mssql")]
            InsertPartialExecutor::MSSQL(exec) => InsertPartialExecutor::MSSQL(exec.default(f)),
            #[cfg(feature = "duckdb")]
            InsertPartialExecutor::DuckDB(exec) => InsertPartialExecutor::DuckDB(exec.default(f)),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            unsupported @ InsertPartialExecutor::Unsupported { .. } => unsupported,
        }
    }

    pub fn to_sql(&self) -> crate::Result<SqlStatement> {
        match self {
            #[cfg(feature = "sqlite")]
            InsertPartialExecutor::Sqlite(exec, _) => exec.to_sql(),
            #[cfg(feature = "postgresql")]
            InsertPartialExecutor::PostgreSQL(exec) => exec.to_sql(),
            #[cfg(feature = "mysql")]
            InsertPartialExecutor::MySQL(exec) => exec.to_sql(),
            #[cfg(feature = "mssql")]
            InsertPartialExecutor::MSSQL(exec) => exec.to_sql(),
            #[cfg(feature = "duckdb")]
            InsertPartialExecutor::DuckDB(exec) => exec.to_sql(),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            InsertPartialExecutor::Unsupported {
                backend, feature, ..
            } => Err(unsupported_feature(*backend, feature)),
        }
    }

    pub async fn execute(self) -> crate::Result<<T as Model>::AutoIncrementKeyType> {
        match self {
            #[cfg(feature = "sqlite")]
            InsertPartialExecutor::Sqlite(exec, _) => exec.execute().await,
            #[cfg(feature = "postgresql")]
            InsertPartialExecutor::PostgreSQL(exec) => exec.execute().await,
            #[cfg(feature = "mysql")]
            InsertPartialExecutor::MySQL(exec) => exec.execute().await,
            #[cfg(feature = "mssql")]
            InsertPartialExecutor::MSSQL(exec) => exec.execute().await,
            #[cfg(feature = "duckdb")]
            InsertPartialExecutor::DuckDB(exec) => exec.execute().await,
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            InsertPartialExecutor::Unsupported {
                backend, feature, ..
            } => Err(unsupported_feature(backend, feature)),
        }
    }
}

/// ClickHouse/InfluxDB 变体的 insert conflict 配置落地(L11):两后端不支持
/// conflict 处理,配置存储到变体字段,由 to_sql / execute 入口统一返回
/// `UnsupportedFeature`,与 to_sql 的拒绝行为一致,不再静默丢弃。
#[cfg(any(feature = "clickhouse", feature = "influxdb"))]
fn insert_conflict_or_default(
    conflict: &mut Option<crate::query::insert::InsertConflict>,
) -> &mut crate::query::insert::InsertConflict {
    conflict.get_or_insert_with(crate::query::insert::InsertConflict::default)
}

/// 已配置的 insert conflict(ClickHouse/InfluxDB execute 入口的拒绝判定)。
#[cfg(any(feature = "clickhouse", feature = "influxdb"))]
fn insert_conflict_is_configured(
    conflict: Option<&crate::query::insert::InsertConflict>,
) -> bool {
    conflict.is_some_and(|conflict| conflict.is_configured())
}

impl<'a, I: crate::model::Insertable + Send + Sync> InsertExecutor<'a, I> {
    /// ClickHouse/InfluxDB 变体的 conflict 配置分支收敛(L22:14 处同构
    /// match 分支合一)。原宏在 match 臂位置展开多条臂的写法非法(宏
    /// 无法生成 match 臂),改为方法:两个后端变体的解构、conflict
    /// 初始化与执行器重建在此统一,调用方分支体以 `FnOnce` 闭包传入
    /// (match 分支互斥,捕获的参数可安全移动)。其余变体(含
    /// Unsupported 哨兵)原样返回。
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    fn with_insert_conflict<F>(self, apply: F) -> Self
    where
        F: FnOnce(&mut crate::query::insert::InsertConflict),
    {
        match self {
            #[cfg(feature = "clickhouse")]
            InsertExecutor::ClickHouse(db, models, mut conflict, marker) => {
                apply(insert_conflict_or_default(&mut conflict));
                InsertExecutor::ClickHouse(db, models, conflict, marker)
            }
            #[cfg(feature = "influxdb")]
            InsertExecutor::InfluxDB(db, models, mut conflict, marker) => {
                apply(insert_conflict_or_default(&mut conflict));
                InsertExecutor::InfluxDB(db, models, conflict, marker)
            }
            other => other,
        }
    }

    pub fn on_conflict<F, C>(self, f: F) -> Self
    where
        F: FnOnce(<I::Model as Model>::Where) -> C,
        C: crate::query::insert::ConflictColumns,
    {
        match self {
            #[cfg(feature = "sqlite")]
            InsertExecutor::Sqlite(exec) => InsertExecutor::Sqlite(exec.on_conflict(f)),
            #[cfg(feature = "sqlite")]
            InsertExecutor::SqliteTxn(exec) => InsertExecutor::SqliteTxn(exec.on_conflict(f)),
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQL(exec) => InsertExecutor::PostgreSQL(exec.on_conflict(f)),
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQLTxn(exec) => {
                InsertExecutor::PostgreSQLTxn(exec.on_conflict(f))
            }
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQL(exec) => InsertExecutor::MySQL(exec.on_conflict(f)),
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQLTxn(exec) => InsertExecutor::MySQLTxn(exec.on_conflict(f)),
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQL(exec) => InsertExecutor::MSSQL(exec.on_conflict(f)),
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQLTxn(exec) => InsertExecutor::MSSQLTxn(exec.on_conflict(f)),
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDB(exec) => InsertExecutor::DuckDB(exec.on_conflict(f)),
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDBTxn(exec) => InsertExecutor::DuckDBTxn(exec.on_conflict(f)),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            exec => exec.with_insert_conflict(|conflict| {
                conflict.target = Some(crate::query::insert::InsertConflictTarget::Columns(
                    f(<I::Model as Model>::Where::default()).conflict_columns(),
                ));
            }),
        }
    }

    pub fn on_constraint<Target>(self, target: Target) -> Self
    where
        Target: crate::query::insert::IntoInsertConflictTarget<I::Model>,
    {
        match self {
            #[cfg(feature = "sqlite")]
            InsertExecutor::Sqlite(exec) => InsertExecutor::Sqlite(exec.on_constraint(target)),
            #[cfg(feature = "sqlite")]
            InsertExecutor::SqliteTxn(exec) => {
                InsertExecutor::SqliteTxn(exec.on_constraint(target))
            }
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQL(exec) => {
                InsertExecutor::PostgreSQL(exec.on_constraint(target))
            }
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQLTxn(exec) => {
                InsertExecutor::PostgreSQLTxn(exec.on_constraint(target))
            }
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQL(exec) => InsertExecutor::MySQL(exec.on_constraint(target)),
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQLTxn(exec) => {
                InsertExecutor::MySQLTxn(exec.on_constraint(target))
            }
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQL(exec) => InsertExecutor::MSSQL(exec.on_constraint(target)),
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQLTxn(exec) => {
                InsertExecutor::MSSQLTxn(exec.on_constraint(target))
            }
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDB(exec) => InsertExecutor::DuckDB(exec.on_constraint(target)),
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDBTxn(exec) => {
                InsertExecutor::DuckDBTxn(exec.on_constraint(target))
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            exec => exec.with_insert_conflict(|conflict| {
                conflict.target = Some(target.into_insert_conflict_target());
            }),
        }
    }

    pub fn conflict_where<F, W>(self, f: F) -> Self
    where
        F: FnOnce(<I::Model as Model>::Where) -> W,
        W: Into<WhereExpr>,
    {
        match self {
            #[cfg(feature = "sqlite")]
            InsertExecutor::Sqlite(exec) => InsertExecutor::Sqlite(exec.conflict_where(f)),
            #[cfg(feature = "sqlite")]
            InsertExecutor::SqliteTxn(exec) => InsertExecutor::SqliteTxn(exec.conflict_where(f)),
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQL(exec) => InsertExecutor::PostgreSQL(exec.conflict_where(f)),
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQLTxn(exec) => {
                InsertExecutor::PostgreSQLTxn(exec.conflict_where(f))
            }
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQL(exec) => InsertExecutor::MySQL(exec.conflict_where(f)),
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQLTxn(exec) => {
                InsertExecutor::MySQLTxn(exec.conflict_where(f))
            }
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQL(exec) => InsertExecutor::MSSQL(exec.conflict_where(f)),
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQLTxn(exec) => {
                InsertExecutor::MSSQLTxn(exec.conflict_where(f))
            }
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDB(exec) => InsertExecutor::DuckDB(exec.conflict_where(f)),
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDBTxn(exec) => {
                InsertExecutor::DuckDBTxn(exec.conflict_where(f))
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            exec => exec.with_insert_conflict(|conflict| {
                conflict.target_filter = Some(crate::query::insert::where_expr_to_filter(f(
                    <I::Model as Model>::Where::default(),
                )));
            }),
        }
    }

    pub fn do_nothing(self) -> Self {
        match self {
            #[cfg(feature = "sqlite")]
            InsertExecutor::Sqlite(exec) => InsertExecutor::Sqlite(exec.do_nothing()),
            #[cfg(feature = "sqlite")]
            InsertExecutor::SqliteTxn(exec) => InsertExecutor::SqliteTxn(exec.do_nothing()),
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQL(exec) => InsertExecutor::PostgreSQL(exec.do_nothing()),
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQLTxn(exec) => {
                InsertExecutor::PostgreSQLTxn(exec.do_nothing())
            }
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQL(exec) => InsertExecutor::MySQL(exec.do_nothing()),
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQLTxn(exec) => InsertExecutor::MySQLTxn(exec.do_nothing()),
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQL(exec) => InsertExecutor::MSSQL(exec.do_nothing()),
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQLTxn(exec) => InsertExecutor::MSSQLTxn(exec.do_nothing()),
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDB(exec) => InsertExecutor::DuckDB(exec.do_nothing()),
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDBTxn(exec) => InsertExecutor::DuckDBTxn(exec.do_nothing()),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            exec => exec.with_insert_conflict(|conflict| {
                conflict.action = Some(crate::query::insert::InsertConflictAction::DoNothing);
            }),
        }
    }

    pub fn do_update(self) -> Self {
        match self {
            #[cfg(feature = "sqlite")]
            InsertExecutor::Sqlite(exec) => InsertExecutor::Sqlite(exec.do_update()),
            #[cfg(feature = "sqlite")]
            InsertExecutor::SqliteTxn(exec) => InsertExecutor::SqliteTxn(exec.do_update()),
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQL(exec) => InsertExecutor::PostgreSQL(exec.do_update()),
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQLTxn(exec) => {
                InsertExecutor::PostgreSQLTxn(exec.do_update())
            }
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQL(exec) => InsertExecutor::MySQL(exec.do_update()),
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQLTxn(exec) => InsertExecutor::MySQLTxn(exec.do_update()),
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQL(exec) => InsertExecutor::MSSQL(exec.do_update()),
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQLTxn(exec) => InsertExecutor::MSSQLTxn(exec.do_update()),
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDB(exec) => InsertExecutor::DuckDB(exec.do_update()),
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDBTxn(exec) => InsertExecutor::DuckDBTxn(exec.do_update()),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            exec => exec.with_insert_conflict(|conflict| {
                conflict.action = Some(crate::query::insert::InsertConflictAction::DoUpdate);
            }),
        }
    }

    pub fn do_update_if<F, W>(self, f: F) -> Self
    where
        F: FnOnce(<I::Model as Model>::Where) -> W,
        W: Into<WhereExpr>,
    {
        match self {
            #[cfg(feature = "sqlite")]
            InsertExecutor::Sqlite(exec) => InsertExecutor::Sqlite(exec.do_update_if(f)),
            #[cfg(feature = "sqlite")]
            InsertExecutor::SqliteTxn(exec) => InsertExecutor::SqliteTxn(exec.do_update_if(f)),
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQL(exec) => InsertExecutor::PostgreSQL(exec.do_update_if(f)),
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQLTxn(exec) => {
                InsertExecutor::PostgreSQLTxn(exec.do_update_if(f))
            }
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQL(exec) => InsertExecutor::MySQL(exec.do_update_if(f)),
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQLTxn(exec) => InsertExecutor::MySQLTxn(exec.do_update_if(f)),
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQL(exec) => InsertExecutor::MSSQL(exec.do_update_if(f)),
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQLTxn(exec) => InsertExecutor::MSSQLTxn(exec.do_update_if(f)),
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDB(exec) => InsertExecutor::DuckDB(exec.do_update_if(f)),
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDBTxn(exec) => InsertExecutor::DuckDBTxn(exec.do_update_if(f)),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            exec => exec.with_insert_conflict(|conflict| {
                let update_filter = crate::query::insert::where_expr_to_filter(f(
                    <I::Model as Model>::Where::default(),
                ));
                conflict.action = Some(crate::query::insert::InsertConflictAction::DoUpdate);
                conflict.update_filter = Some(update_filter);
            }),
        }
    }

    pub fn set<F>(self, f: F) -> Self
    where
        F: FnOnce(&mut <I::Model as Model>::Update),
    {
        match self {
            #[cfg(feature = "sqlite")]
            InsertExecutor::Sqlite(exec) => InsertExecutor::Sqlite(exec.set(f)),
            #[cfg(feature = "sqlite")]
            InsertExecutor::SqliteTxn(exec) => InsertExecutor::SqliteTxn(exec.set(f)),
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQL(exec) => InsertExecutor::PostgreSQL(exec.set(f)),
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQLTxn(exec) => {
                InsertExecutor::PostgreSQLTxn(exec.set(f))
            }
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQL(exec) => InsertExecutor::MySQL(exec.set(f)),
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQLTxn(exec) => InsertExecutor::MySQLTxn(exec.set(f)),
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQL(exec) => InsertExecutor::MSSQL(exec.set(f)),
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQLTxn(exec) => InsertExecutor::MSSQLTxn(exec.set(f)),
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDB(exec) => InsertExecutor::DuckDB(exec.set(f)),
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDBTxn(exec) => InsertExecutor::DuckDBTxn(exec.set(f)),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            exec => exec.with_insert_conflict(|conflict| {
                let mut update = <I::Model as Model>::Update::default();
                f(&mut update);
                conflict
                    .action
                    .get_or_insert(crate::query::insert::InsertConflictAction::DoUpdate);
                conflict.assignments.extend(
                    <<I::Model as Model>::Update as crate::query::update::UpdateFields>::assignments(
                        &update,
                    ),
                );
            }),
        }
    }

    pub fn to_sql(&self) -> crate::Result<SqlStatement> {
        match self {
            #[cfg(feature = "sqlite")]
            InsertExecutor::Sqlite(exec) => exec.to_sql(),
            #[cfg(feature = "sqlite")]
            InsertExecutor::SqliteTxn(exec) => exec.to_sql(),
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQL(exec) => exec.to_sql(),
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQLTxn(exec) => exec.to_sql(),
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQL(exec) => exec.to_sql(),
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQLTxn(exec) => exec.to_sql(),
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQL(exec) => exec.to_sql(),
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQLTxn(exec) => exec.to_sql(),
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDB(exec) => exec.to_sql(),
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDBTxn(exec) => exec.to_sql(),
            #[cfg(feature = "clickhouse")]
            InsertExecutor::ClickHouse(_, models, conflict, _) => {
                // to_sql 渲染等价的多行 VALUES 文本(可观测性用途);
                // 实际执行走 insert_model_rows 的原生流式 INSERT。
                let refs = models.as_refs();
                let statements = common_helpers::build_insert_statements_with_conflict::<I::Model>(
                    super::super::DbType::ClickHouse,
                    &refs,
                    conflict.as_ref(),
                )?;
                Ok(SqlStatement::batch(
                    super::super::DbType::ClickHouse,
                    statements
                        .into_iter()
                        .map(|statement| SingleSqlStatement::new(statement.sql, statement.params))
                        .collect(),
                ))
            }
            #[cfg(feature = "influxdb")]
            InsertExecutor::Unsupported {
                backend,
                feature,
                ..
            } => Err(unsupported_feature(*backend, feature)),
            #[cfg(feature = "influxdb")]
            InsertExecutor::InfluxDB(..) => Err(unsupported_feature(
                super::super::DbType::InfluxDB,
                "insert to_sql (InfluxDB writes use Line Protocol over HTTP)",
            )),
        }
    }

    pub async fn execute(
        self,
    ) -> crate::Result<<I::Model as crate::model::Model>::AutoIncrementKeyType> {
        match self {
            #[cfg(feature = "sqlite")]
            InsertExecutor::Sqlite(exec) => exec.execute().await,
            #[cfg(feature = "sqlite")]
            InsertExecutor::SqliteTxn(exec) => exec.execute().await,
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQL(exec) => exec.execute().await,
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQLTxn(exec) => exec.execute().await,
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQL(exec) => exec.execute().await,
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQLTxn(exec) => exec.execute().await,
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQL(exec) => exec.execute().await,
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQLTxn(exec) => exec.execute().await,
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDB(exec) => exec.execute().await,
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDBTxn(exec) => exec.execute().await,
            #[cfg(feature = "clickhouse")]
            InsertExecutor::ClickHouse(db, mut models, conflict, _) => {
                // ClickHouse 不支持 insert conflict:已配置的 conflict 配置在
                // 入口直接拒绝(与 to_sql 行为一致),不再静默丢弃
                if insert_conflict_is_configured(conflict.as_ref()) {
                    return Err(unsupported_feature(
                        super::super::DbType::ClickHouse,
                        "insert conflict handling",
                    ));
                }
                if models.as_refs().is_empty() {
                    return Ok(<I::Model as Model>::AutoIncrementKeyType::default());
                }

                let ctx = crate::HookContext::new(crate::HookOperation::Insert);
                // 钩子先于写入执行:钩子可修改模型字段,载荷必须在
                // before_insert 之后序列化
                models.run_before_insert(ctx).await?;
                {
                    let refs = models.as_refs();
                    db.insert_model_rows::<I::Model>(&refs).await?;
                }
                models.run_after_insert(ctx).await?;
                Ok(<I::Model as Model>::AutoIncrementKeyType::default())
            }
            #[cfg(feature = "influxdb")]
            InsertExecutor::Unsupported {
                backend,
                feature,
                models,
                ..
            } => {
                drop(models);
                Err(unsupported_feature(backend, feature))
            }
            #[cfg(feature = "influxdb")]
            InsertExecutor::InfluxDB(db, mut models, conflict, _) => {
                // InfluxDB 不支持 insert conflict:已配置的 conflict 配置在
                // 入口直接拒绝(与 to_sql 行为一致),不再静默丢弃
                if insert_conflict_is_configured(conflict.as_ref()) {
                    return Err(unsupported_feature(
                        super::super::DbType::InfluxDB,
                        "insert conflict handling",
                    ));
                }
                if models.as_refs().is_empty() {
                    return Ok(<I::Model as Model>::AutoIncrementKeyType::default());
                }

                crate::abstract_layer::influxdb_backend::validate_influx_model::<I::Model>(
                    super::super::DbType::InfluxDB,
                )?;
                let ctx = crate::HookContext::new(crate::HookOperation::Insert);
                // 钩子可修改模型字段,Line Protocol 必须在 before_insert 之后渲染
                models.run_before_insert(ctx).await?;
                {
                    let refs = models.as_refs();
                    let lines = crate::abstract_layer::influxdb_backend::render_line_protocol::<
                        I::Model,
                    >(&refs)?;
                    db.write_lines_with_policy(
                        &lines,
                        crate::abstract_layer::influxdb_backend::model_retention_policy_name::<
                            I::Model,
                        >()
                        .as_deref(),
                    )
                    .await?;
                }
                models.run_after_insert(ctx).await?;
                Ok(<I::Model as Model>::AutoIncrementKeyType::default())
            }
        }
    }

    pub fn without_hooks(self) -> crate::WithoutHooksExecutor<Self> {
        crate::WithoutHooksExecutor(self)
    }

    pub async fn returning(self) -> crate::Result<Vec<I::Model>> {
        // 能力矩阵优先:dml_returning=false 的后端(MySQL/QuestDB/ClickHouse/
        // InfluxDB)统一以 "DML RETURNING" 拒绝;PostgreSQL 变体经后端
        // db_type() 按运行时类型判定(QuestDB 复用 PG 连接)。
        let backend = match &self {
            #[cfg(feature = "sqlite")]
            InsertExecutor::Sqlite(_) => super::super::DbType::Sqlite,
            #[cfg(feature = "sqlite")]
            InsertExecutor::SqliteTxn(_) => super::super::DbType::Sqlite,
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQL(exec) => exec.db_type(),
            // 事务只存在于 transactions=true 的真实 PostgreSQL 连接上,
            // 无 QuestDB 运行时分支。
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQLTxn(_) => super::super::DbType::PostgreSQL,
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQL(_) => super::super::DbType::MySQL,
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQLTxn(_) => super::super::DbType::MySQL,
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQL(_) => super::super::DbType::MSSQL,
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQLTxn(_) => super::super::DbType::MSSQL,
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDB(_) => super::super::DbType::DuckDB,
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDBTxn(_) => super::super::DbType::DuckDB,
            #[cfg(feature = "clickhouse")]
            InsertExecutor::ClickHouse(..) => super::super::DbType::ClickHouse,
            #[cfg(feature = "influxdb")]
            InsertExecutor::Unsupported { backend, .. } => *backend,
            #[cfg(feature = "influxdb")]
            InsertExecutor::InfluxDB(..) => super::super::DbType::InfluxDB,
        };
        Capabilities::ensure(backend, |caps| caps.dml_returning, "DML RETURNING")?;
        match self {
            #[cfg(feature = "sqlite")]
            InsertExecutor::Sqlite(exec) => exec.returning().await,
            #[cfg(feature = "sqlite")]
            InsertExecutor::SqliteTxn(_) => Err(unsupported_feature(
                super::super::DbType::Sqlite,
                "DML RETURNING inside transactions",
            )),
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQL(exec) => exec.returning().await,
            #[cfg(feature = "postgresql")]
            InsertExecutor::PostgreSQLTxn(_) => Err(unsupported_feature(
                super::super::DbType::PostgreSQL,
                "DML RETURNING inside transactions",
            )),
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQL(exec) => exec.returning().await,
            #[cfg(feature = "mysql")]
            InsertExecutor::MySQLTxn(_) => Err(unsupported_feature(
                super::super::DbType::MySQL,
                "DML RETURNING inside transactions",
            )),
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQL(exec) => exec.returning().await,
            #[cfg(feature = "mssql")]
            InsertExecutor::MSSQLTxn(_) => Err(unsupported_feature(
                super::super::DbType::MSSQL,
                "DML RETURNING inside transactions",
            )),
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDB(exec) => exec.returning().await,
            #[cfg(feature = "duckdb")]
            InsertExecutor::DuckDBTxn(_) => Err(unsupported_feature(
                super::super::DbType::DuckDB,
                "DML RETURNING inside transactions",
            )),
            #[cfg(feature = "clickhouse")]
            InsertExecutor::ClickHouse(..) => Err(unsupported_feature(
                super::super::DbType::ClickHouse,
                "DML RETURNING",
            )),
            #[cfg(feature = "influxdb")]
            InsertExecutor::Unsupported {
                backend,
                feature,
                ..
            } => Err(unsupported_feature(backend, feature)),
            #[cfg(feature = "influxdb")]
            InsertExecutor::InfluxDB(..) => Err(unsupported_feature(
                super::super::DbType::InfluxDB,
                "DML RETURNING",
            )),
        }
    }
}

/// `db.insert(&models).await` 直接执行(委托 [`InsertExecutor::execute`]),
/// 与后端层执行器和文档示例的写法保持一致。
/// 注意:Delete/Update 执行器的 `IntoFuture` 由 `impl_unified_delete_executor!`
/// / `impl_unified_update_executor!` 宏生成,此处不再重复实现。
impl<'a, I> std::future::IntoFuture for InsertExecutor<'a, I>
where
    I: crate::model::Insertable + Send + Sync,
    <I::Model as crate::model::Model>::AutoIncrementKeyType: Send,
    <I as crate::model::Insertable>::Model: Send + Sync,
    Self: 'a,
{
    type Output = crate::Result<<I::Model as crate::model::Model>::AutoIncrementKeyType>;
    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(self.execute())
    }
}

/// 统一的 InsertOrUpdateExecutor 枚举
pub enum InsertOrUpdateExecutor<'a, I: crate::model::Insertable> {
    #[cfg(feature = "sqlite")]
    Sqlite(sqlite_backend::InsertOrUpdateExecutor<'a, I>),
    /// 事务路径变体:原 `TransactionInsertOrUpdateExecutor` 已合并入本枚举。
    #[cfg(feature = "sqlite")]
    SqliteTxn(sqlite_backend::TransactionInsertOrUpdateExecutor<'a, I>),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::InsertOrUpdateExecutor<'a, I>),
    /// 事务路径变体(原 `TransactionInsertOrUpdateExecutor` 的 PostgreSQL 分支)。
    #[cfg(feature = "postgresql")]
    PostgreSQLTxn(postgresql_backend::TransactionInsertOrUpdateExecutor<'a, I>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::InsertOrUpdateExecutor<'a, I>),
    /// 事务路径变体(原 `TransactionInsertOrUpdateExecutor` 的 MySQL 分支)。
    #[cfg(feature = "mysql")]
    MySQLTxn(mysql_backend::TransactionInsertOrUpdateExecutor<'a, I>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::InsertOrUpdateExecutor<'a, I>),
    /// 事务路径变体(原 `TransactionInsertOrUpdateExecutor` 的 MSSQL 分支)。
    #[cfg(feature = "mssql")]
    MSSQLTxn(mssql_backend::TransactionInsertOrUpdateExecutor<'a, I>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::InsertOrUpdateExecutor<'a, I>),
    /// 事务路径变体(原 `TransactionInsertOrUpdateExecutor` 的 DuckDB 分支)。
    #[cfg(feature = "duckdb")]
    DuckDBTxn(duckdb_backend::TransactionInsertOrUpdateExecutor<'a, I>),
    /// 能力矩阵门控产物:`insert_conflict: false` 的后端在
    /// [`Database::insert_or_update`] 构造时落入该变体。
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        _marker: std::marker::PhantomData<&'a I>,
    },
}

/// 旧事务插入或更新执行器名过渡别名(已合并为 [`InsertOrUpdateExecutor`],
/// 保留 re-export 以兼容现有导入路径)。
#[deprecated(
    since = "0.2.12",
    note = "TransactionInsertOrUpdateExecutor 已合并为 InsertOrUpdateExecutor,请改用 InsertOrUpdateExecutor"
)]
pub type TransactionInsertOrUpdateExecutor<'a, I> = InsertOrUpdateExecutor<'a, I>;

pub struct InsertGraphExecutor<'a, T: crate::model::GraphWritable> {
    db: &'a Database,
    model: &'a mut T,
}

pub struct UpdateGraphExecutor<'a, T: crate::model::GraphWritable> {
    db: &'a Database,
    model: &'a mut T,
}

impl<'a, I: crate::model::Insertable + Send + Sync> InsertOrUpdateExecutor<'a, I> {
    pub fn to_sql(&self) -> crate::Result<SqlStatement> {
        match self {
            #[cfg(feature = "sqlite")]
            InsertOrUpdateExecutor::Sqlite(exec) => exec.to_sql(),
            #[cfg(feature = "sqlite")]
            InsertOrUpdateExecutor::SqliteTxn(exec) => exec.to_sql(),
            #[cfg(feature = "postgresql")]
            InsertOrUpdateExecutor::PostgreSQL(exec) => exec.to_sql(),
            #[cfg(feature = "postgresql")]
            InsertOrUpdateExecutor::PostgreSQLTxn(exec) => exec.to_sql(),
            #[cfg(feature = "mysql")]
            InsertOrUpdateExecutor::MySQL(exec) => exec.to_sql(),
            #[cfg(feature = "mysql")]
            InsertOrUpdateExecutor::MySQLTxn(exec) => exec.to_sql(),
            #[cfg(feature = "mssql")]
            InsertOrUpdateExecutor::MSSQL(exec) => exec.to_sql(),
            #[cfg(feature = "mssql")]
            InsertOrUpdateExecutor::MSSQLTxn(exec) => exec.to_sql(),
            #[cfg(feature = "duckdb")]
            InsertOrUpdateExecutor::DuckDB(exec) => exec.to_sql(),
            #[cfg(feature = "duckdb")]
            InsertOrUpdateExecutor::DuckDBTxn(exec) => exec.to_sql(),
            InsertOrUpdateExecutor::Unsupported {
                backend, feature, ..
            } => Err(unsupported_feature(*backend, feature)),
        }
    }

    pub async fn execute(self) -> crate::Result<()> {
        match self {
            #[cfg(feature = "sqlite")]
            InsertOrUpdateExecutor::Sqlite(exec) => exec.execute().await,
            #[cfg(feature = "sqlite")]
            InsertOrUpdateExecutor::SqliteTxn(exec) => exec.execute().await,
            #[cfg(feature = "postgresql")]
            InsertOrUpdateExecutor::PostgreSQL(exec) => exec.execute().await,
            #[cfg(feature = "postgresql")]
            InsertOrUpdateExecutor::PostgreSQLTxn(exec) => exec.execute().await,
            #[cfg(feature = "mysql")]
            InsertOrUpdateExecutor::MySQL(exec) => exec.execute().await,
            #[cfg(feature = "mysql")]
            InsertOrUpdateExecutor::MySQLTxn(exec) => exec.execute().await,
            #[cfg(feature = "mssql")]
            InsertOrUpdateExecutor::MSSQL(exec) => exec.execute().await.map(|_| ()),
            #[cfg(feature = "mssql")]
            InsertOrUpdateExecutor::MSSQLTxn(exec) => exec.execute().await,
            #[cfg(feature = "duckdb")]
            InsertOrUpdateExecutor::DuckDB(exec) => exec.execute().await.map(|_| ()),
            #[cfg(feature = "duckdb")]
            InsertOrUpdateExecutor::DuckDBTxn(exec) => exec.execute().await,
            InsertOrUpdateExecutor::Unsupported {
                backend, feature, ..
            } => Err(unsupported_feature(backend, feature)),
        }
    }

    pub fn without_hooks(self) -> crate::WithoutHooksExecutor<Self> {
        crate::WithoutHooksExecutor(self)
    }
}

/// 错误处理兜底路径中的回滚:失败不能完全静默,至少记录日志,
/// 避免连接带着未关闭的事务回池而无任何痕迹。
///
/// L20:Database / 事务 / 池连接三条路径的回滚失败日志统一走此处
/// (savepoint 的 ROLLBACK TO / RELEASE 失败同样)。
/// 泛型化返回值:调用方既有 `Result<()>`(事务回滚)也有 `Result<u64>`
/// (savepoint 的 execute_sql),仅日志用途,不关心成功值。
pub(crate) fn log_rollback_failure<T>(result: crate::Result<T>) {
    if let Err(err) = result {
        eprintln!("[ormer] rollback failed during error handling: {err}");
    }
}

/// 事务闭包的公共收尾(L20):成功提交、失败回滚(回滚失败走统一日志,
/// 不覆盖主错误)。[`Database::transaction_opts`] 与池连接的
/// `PooledConnection::transaction_opts` 共用。
pub(crate) async fn run_txn_closure<R, F>(txn: Transaction<'_>, f: F) -> crate::Result<R>
where
    F: for<'tx> FnOnce(&'tx mut Transaction<'_>) -> TransactionFuture<'tx, R>,
{
    let mut txn = txn;
    match f(&mut txn).await {
        Ok(value) => {
            txn.commit().await?;
            Ok(value)
        }
        Err(err) => {
            log_rollback_failure(txn.rollback().await);
            Err(err)
        }
    }
}

/// "先 BEGIN 再应用事务选项"的公共路径(L20):应用失败时回滚并返回
/// 原错误(回滚失败走统一日志)。MySQL 以外的后端共用;
/// [`Database::begin_opts`] 与池连接的 `begin_then_apply` 均委托此处。
pub(crate) async fn apply_transaction_options_or_rollback(
    txn: Transaction<'_>,
    options: TransactionOptions,
) -> crate::Result<Transaction<'_>> {
    let mut txn = txn;
    if let Err(err) = apply_transaction_options(&mut txn, options).await {
        log_rollback_failure(txn.rollback().await);
        return Err(err);
    }
    Ok(txn)
}

impl<'a, T> InsertGraphExecutor<'a, T>
where
    T: crate::model::GraphWritable + Send + Sync + 'a,
    <T as Model>::AutoIncrementKeyType: Into<crate::model::Value>,
{
    pub async fn execute(self) -> crate::Result<()> {
        let mut tx = self.db.begin().await?;
        if let Err(err) = async {
            let key = tx.insert(&*self.model).execute().await?;
            let key_value = crate::model::graph_auto_increment_key_value(key);
            if !crate::model::graph_is_no_auto_increment_key(&key_value) {
                self.model
                    .assign_column_value(<T as Model>::primary_key_columns()[0], key_value)?;
            }
            <T as crate::model::GraphWritable>::insert_graph_relations(&mut tx, self.model).await
        }
        .await
        {
            log_rollback_failure(tx.rollback().await);
            return Err(err);
        }
        tx.commit().await
    }
}

impl<'a, T> UpdateGraphExecutor<'a, T>
where
    T: crate::model::GraphWritable + Send + Sync + 'a,
{
    pub async fn execute(self) -> crate::Result<u64> {
        let mut tx = self.db.begin().await?;
        let affected = match async {
            #[cfg(feature = "duckdb")]
            let affected = if tx.db_type() == super::super::DbType::DuckDB {
                match common_helpers::model_update_plan(&*self.model, None) {
                    Some(plan) => {
                        let statement =
                            common_helpers::build_duckdb_graph_update_sql::<T>(&*self.model, &plan)?;
                        match &mut tx {
                            Transaction::DuckDB(txn) => {
                                let executor = txn.update::<T>();
                                <duckdb_backend::UpdateExecutor<T> as super::SqlExecutor>::execute_with_sql(
                                    executor,
                                    SqlStatement::single(
                                        super::super::DbType::DuckDB,
                                        statement.sql,
                                        statement.params,
                                    ),
                                )
                                .await?
                            }
                            // db_type() 已判定为 DuckDB,其余变体不应出现;
                            // 返回错误而非 panic,防御事务枚举被混用。
                            _ => {
                                return Err(crate::OrmerError::invalid_operation(
                                    "DuckDB graph update dispatched to a non-DuckDB transaction",
                                ));
                            }
                        }
                    }
                    None => 0,
                }
            } else {
                tx.update::<T>().set_model(&*self.model).execute().await?
            };
            #[cfg(not(feature = "duckdb"))]
            let affected = tx.update::<T>().set_model(&*self.model).execute().await?;
            <T as crate::model::GraphWritable>::update_graph_relations(&mut tx, self.model).await?;
            Ok::<u64, crate::OrmerError>(affected)
        }
        .await
        {
            Ok(affected) => affected,
            Err(err) => {
                log_rollback_failure(tx.rollback().await);
                return Err(err);
            }
        };
        tx.commit().await?;
        Ok(affected)
    }
}

/// Save 执行器:按 dirty 列更新 + 图关系同步(R3 合并)。
///
/// [`Database::save`] 走自开事务(结束时提交/回滚),[`Transaction::save`]
/// 使用外部事务(写完不提交不回滚,由调用方决定事务边界)。
pub struct SaveExecutor<'a, T: WritableModel + crate::model::GraphWritable> {
    conn: SaveConn<'a, T>,
    model: &'a mut Tracked<T>,
}

/// Save 执行器的连接句柄(R3 合并;Database / 池连接 / 事务三条构造路径)。
///
/// 事务路径的写核心([`save_dirty_columns_and_relations`] → 图同步链路)要求
/// `&mut Transaction<'tx>`;`'tx` 与外层借用生命周期不同,且 `&'op mut
/// Transaction<'a>` 无法收缩成 `&'op mut Transaction<'op>`(可变引用不变性)。
/// 因此在 [`Transaction::save`] 构造时把事务句柄装进擦除 `'tx` 的运行闭包,
/// [`SaveExecutor`] 的公开形状保持 `SaveExecutor<'a, T>` 不变;
/// SQL 预览同样在构造时渲染(dirty 列集合在执行器存续期被独占借用,不可再变,
/// 尽早渲染与调用时惰性渲染结果一致)。
///
/// 池连接路径(L24)与事务路径同构(预渲染 SQL + 擦除启动闭包,池连接的
/// 内层生命周期同样需要擦除),但语义与 `Db` 一致:写核心自开事务、
/// 结束时提交/回滚。
enum SaveConn<'a, T: WritableModel + crate::model::GraphWritable> {
    Db(&'a Database),
    Pooled {
        sql: crate::Result<SqlStatement>,
        /// 在池连接自开的事务上执行写核心,并把模型句柄归还调用方。
        run: SaveTxnRun<'a, T>,
    },
    Txn {
        sql: crate::Result<SqlStatement>,
        /// 在给定事务上执行写核心,并把模型句柄归还调用方
        /// (后续 accept_changes / after_update 仍由执行器统一调度)。
        run: SaveTxnRun<'a, T>,
    },
}

/// 事务路径写核心的擦除启动器:消费 `&'a mut Tracked<T>`,
/// 返回 (写结果, 模型句柄)。
///
/// 闭包只捕获事务句柄(模型是参数),因此外层 `+ Send` 仅要求
/// `Transaction: Send`;返回的 future 不标注 `Send`,与合并前
/// `TransactionSaveExecutor::execute` 的条件 Send 语义一致
/// (`SaveExecutor` 仍在 `T: Send` 时自动满足 `Send`)。
/// 写核心闭包返回的 future:产出 (写结果, 归还的模型句柄)。
type SaveTxnFuture<'a, T> =
    Pin<Box<dyn Future<Output = (crate::Result<u64>, &'a mut Tracked<T>)> + 'a>>;

type SaveTxnRun<'a, T> = Box<dyn FnOnce(&'a mut Tracked<T>) -> SaveTxnFuture<'a, T> + Send + 'a>;

/// Save 执行器两条路径共用的收尾:写成功后接受 dirty 变更。
fn finish_save<T: crate::model::Model>(affected: u64, model: &mut Tracked<T>) -> crate::Result<u64> {
    if affected > 0 {
        model.accept_changes();
    }
    Ok(affected)
}

impl<'a, T: WritableModel + crate::model::Model + crate::model::GraphWritable>
    SaveExecutor<'a, T>
{
    pub fn to_sql(&self) -> crate::Result<SqlStatement> {
        match &self.conn {
            SaveConn::Db(db) => {
                let fields = self.model.dirty_columns();
                if fields.is_empty() {
                    return Ok(SqlStatement::batch(db.db_type(), Vec::new()));
                }
                db.update::<T>()
                    .set_model_columns(self.model.as_model(), &fields)
                    .to_sql()
            }
            // 事务 / 池连接路径构造时已渲染,dirty 列在执行器存续期不可再变
            SaveConn::Txn { sql, .. } | SaveConn::Pooled { sql, .. } => sql.clone(),
        }
    }

    pub async fn execute(self) -> crate::Result<u64> {
        let SaveExecutor { conn, mut model } = self;
        let affected = match conn {
            // 自开事务:写入核心共享(R3 合并),结束时提交/回滚
            SaveConn::Db(db) => {
                let mut tx = db.begin().await?;
                match save_dirty_columns_and_relations(&mut tx, model).await {
                    Ok(affected) => {
                        tx.commit().await?;
                        affected
                    }
                    Err(err) => {
                        log_rollback_failure(tx.rollback().await);
                        return Err(err);
                    }
                }
            }
            // 外部事务:写完不提交不回滚,由调用方决定事务边界;
            // 池连接:闭包内自开事务并提交/回滚(L24)
            SaveConn::Txn { run, .. } | SaveConn::Pooled { run, .. } => {
                let (result, m) = run(model).await;
                model = m;
                result?
            }
        };
        finish_save(affected, model)
    }

    /// 同义词,等价于 [`Self::execute`]。
    #[deprecated(since = "0.2.11", note = "use `execute()` instead")]
    pub async fn exec(self) -> crate::Result<u64> {
        self.execute().await
    }

    pub async fn execute_with_hooks(self) -> crate::Result<u64>
    where
        T: crate::BeforeUpdate + crate::AfterUpdate + Send + Sync,
    {
        let SaveExecutor { conn, mut model } = self;
        let mut ctx = crate::HookContext::new(crate::HookOperation::Update);
        // 事务路径携带 `.transaction()` 标记(与合并前事务版语义一致)
        if matches!(conn, SaveConn::Txn { .. }) {
            ctx = ctx.transaction();
        }
        // 与 Update/Delete 执行器同语义:受全局 without_hooks 范围开关控制
        if ctx.hooks_enabled() {
            crate::BeforeUpdate::before_update(model.as_model_mut(), &mut ctx).await?;
        }

        let affected = match conn {
            // 自开事务:after_update 在提交前执行,失败会回滚(与合并前一致)
            SaveConn::Db(db) => {
                let mut tx = db.begin().await?;
                let result = async {
                    let affected =
                        save_dirty_columns_and_relations(&mut tx, model).await?;
                    if affected > 0 && ctx.hooks_enabled() {
                        crate::AfterUpdate::after_update(model.as_model(), &mut ctx).await?;
                    }
                    Ok::<u64, crate::OrmerError>(affected)
                }
                .await;
                match result {
                    Ok(affected) => {
                        tx.commit().await?;
                        affected
                    }
                    Err(err) => {
                        log_rollback_failure(tx.rollback().await);
                        return Err(err);
                    }
                }
            }
            // 外部事务:写完不提交不回滚,由调用方决定事务边界;
            // 池连接:闭包内自开事务并提交/回滚(L24)
            SaveConn::Txn { run, .. } | SaveConn::Pooled { run, .. } => {
                let (result, m) = run(model).await;
                model = m;
                let affected = result?;
                if affected > 0 && ctx.hooks_enabled() {
                    crate::AfterUpdate::after_update(model.as_model(), &mut ctx).await?;
                }
                affected
            }
        };
        finish_save(affected, model)
    }

    /// 跳过本次保存的钩子(等价于在 [`Self::execute_with_hooks`] 外层
    /// 包 `without_hooks` 范围),与其他写入执行器的语义一致。
    pub fn without_hooks(self) -> crate::WithoutHooksExecutor<Self> {
        crate::WithoutHooksExecutor(self)
    }
}

/// 统一的 InsertOrIgnoreExecutor 枚举
pub enum InsertOrIgnoreExecutor<'a, I: crate::model::Insertable> {
    #[cfg(feature = "sqlite")]
    Sqlite(sqlite_backend::InsertOrIgnoreExecutor<'a, I>),
    /// 事务路径变体(原 `TransactionInsertOrIgnoreExecutor` 的 SQLite 分支)。
    #[cfg(feature = "sqlite")]
    SqliteTxn(sqlite_backend::TransactionInsertOrIgnoreExecutor<'a, I>),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::InsertOrIgnoreExecutor<'a, I>),
    /// 事务路径变体(原 `TransactionInsertOrIgnoreExecutor` 的 PostgreSQL 分支)。
    #[cfg(feature = "postgresql")]
    PostgreSQLTxn(postgresql_backend::TransactionInsertOrIgnoreExecutor<'a, I>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::InsertOrIgnoreExecutor<'a, I>),
    /// 事务路径变体(原 `TransactionInsertOrIgnoreExecutor` 的 MySQL 分支)。
    #[cfg(feature = "mysql")]
    MySQLTxn(mysql_backend::TransactionInsertOrIgnoreExecutor<'a, I>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::InsertOrIgnoreExecutor<'a, I>),
    /// 事务路径变体(原 `TransactionInsertOrIgnoreExecutor` 的 MSSQL 分支)。
    #[cfg(feature = "mssql")]
    MSSQLTxn(mssql_backend::TransactionInsertOrIgnoreExecutor<'a, I>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::InsertOrIgnoreExecutor<'a, I>),
    /// 事务路径变体(原 `TransactionInsertOrIgnoreExecutor` 的 DuckDB 分支)。
    #[cfg(feature = "duckdb")]
    DuckDBTxn(duckdb_backend::TransactionInsertOrIgnoreExecutor<'a, I>),
    /// 能力矩阵门控产物:`insert_ignore: false` 的后端在
    /// [`Database::insert_or_ignore`] 构造时落入该变体。
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        _marker: std::marker::PhantomData<&'a I>,
    },
}

/// 旧事务插入或忽略执行器名过渡别名(已合并为 [`InsertOrIgnoreExecutor`],
/// 保留 re-export 以兼容现有导入路径)。
#[deprecated(
    since = "0.2.12",
    note = "TransactionInsertOrIgnoreExecutor 已合并为 InsertOrIgnoreExecutor,请改用 InsertOrIgnoreExecutor"
)]
pub type TransactionInsertOrIgnoreExecutor<'a, I> = InsertOrIgnoreExecutor<'a, I>;

impl<'a, I: crate::model::Insertable + Send + Sync> InsertOrIgnoreExecutor<'a, I> {
    pub fn to_sql(&self) -> crate::Result<SqlStatement> {
        match self {
            #[cfg(feature = "sqlite")]
            InsertOrIgnoreExecutor::Sqlite(exec) => exec.to_sql(),
            #[cfg(feature = "sqlite")]
            InsertOrIgnoreExecutor::SqliteTxn(exec) => exec.to_sql(),
            #[cfg(feature = "postgresql")]
            InsertOrIgnoreExecutor::PostgreSQL(exec) => exec.to_sql(),
            #[cfg(feature = "postgresql")]
            InsertOrIgnoreExecutor::PostgreSQLTxn(exec) => exec.to_sql(),
            #[cfg(feature = "mysql")]
            InsertOrIgnoreExecutor::MySQL(exec) => exec.to_sql(),
            #[cfg(feature = "mysql")]
            InsertOrIgnoreExecutor::MySQLTxn(exec) => exec.to_sql(),
            #[cfg(feature = "mssql")]
            InsertOrIgnoreExecutor::MSSQL(exec) => exec.to_sql(),
            #[cfg(feature = "mssql")]
            InsertOrIgnoreExecutor::MSSQLTxn(exec) => exec.to_sql(),
            #[cfg(feature = "duckdb")]
            InsertOrIgnoreExecutor::DuckDB(exec) => exec.to_sql(),
            #[cfg(feature = "duckdb")]
            InsertOrIgnoreExecutor::DuckDBTxn(exec) => exec.to_sql(),
            InsertOrIgnoreExecutor::Unsupported {
                backend, feature, ..
            } => Err(unsupported_feature(*backend, feature)),
        }
    }

    pub async fn execute(self) -> crate::Result<()> {
        match self {
            #[cfg(feature = "sqlite")]
            InsertOrIgnoreExecutor::Sqlite(exec) => exec.execute().await,
            #[cfg(feature = "sqlite")]
            InsertOrIgnoreExecutor::SqliteTxn(exec) => exec.execute().await,
            #[cfg(feature = "postgresql")]
            InsertOrIgnoreExecutor::PostgreSQL(exec) => exec.execute().await,
            #[cfg(feature = "postgresql")]
            InsertOrIgnoreExecutor::PostgreSQLTxn(exec) => exec.execute().await,
            #[cfg(feature = "mysql")]
            InsertOrIgnoreExecutor::MySQL(exec) => exec.execute().await,
            #[cfg(feature = "mysql")]
            InsertOrIgnoreExecutor::MySQLTxn(exec) => exec.execute().await,
            #[cfg(feature = "mssql")]
            InsertOrIgnoreExecutor::MSSQL(exec) => exec.execute().await.map(|_| ()),
            #[cfg(feature = "mssql")]
            InsertOrIgnoreExecutor::MSSQLTxn(exec) => exec.execute().await,
            #[cfg(feature = "duckdb")]
            InsertOrIgnoreExecutor::DuckDB(exec) => exec.execute().await.map(|_| ()),
            #[cfg(feature = "duckdb")]
            InsertOrIgnoreExecutor::DuckDBTxn(exec) => exec.execute().await,
            InsertOrIgnoreExecutor::Unsupported {
                backend, feature, ..
            } => Err(unsupported_feature(backend, feature)),
        }
    }

    pub fn without_hooks(self) -> crate::WithoutHooksExecutor<Self> {
        crate::WithoutHooksExecutor(self)
    }
}

impl Database {
    pub fn replicated(db_type: super::super::DbType) -> ReplicatedDatabaseBuilder {
        ReplicatedDatabaseBuilder::new(db_type)
    }

    pub fn sql_trace(&self) -> crate::SqlTraceBuilder {
        crate::global_sql_trace().builder()
    }

    /// 连接到数据库,根据 DbType 选择后端
    pub async fn connect(
        db_type: super::super::DbType,
        connection_string: &str,
    ) -> crate::Result<Self> {
        match db_type {
            #[cfg(feature = "sqlite")]
            super::super::DbType::Sqlite => {
                let db = sqlite_backend::Database::connect(db_type, connection_string).await?;
                Ok(Database::Sqlite(db))
            }
            #[cfg(feature = "postgresql")]
            super::super::DbType::PostgreSQL => {
                let db = postgresql_backend::Database::connect(db_type, connection_string).await?;
                Ok(Database::PostgreSQL(db))
            }
            #[cfg(feature = "questdb")]
            super::super::DbType::QuestDB => {
                let db = postgresql_backend::Database::connect(db_type, connection_string).await?;
                Ok(Database::PostgreSQL(db))
            }
            #[cfg(feature = "mysql")]
            super::super::DbType::MySQL => {
                let db = mysql_backend::Database::connect(db_type, connection_string).await?;
                Ok(Database::MySQL(db))
            }
            #[cfg(feature = "mssql")]
            super::super::DbType::MSSQL => {
                let db = mssql_backend::Database::connect(db_type, connection_string).await?;
                Ok(Database::MSSQL(db))
            }
            #[cfg(feature = "duckdb")]
            super::super::DbType::DuckDB => {
                let db = duckdb_backend::Database::connect(db_type, connection_string).await?;
                Ok(Database::DuckDB(db))
            }
            #[cfg(feature = "clickhouse")]
            super::super::DbType::ClickHouse => {
                let db = super::super::clickhouse_backend::Database::connect(connection_string)?;
                Ok(Database::ClickHouse(db))
            }
            #[cfg(feature = "influxdb")]
            super::super::DbType::InfluxDB => {
                let db = super::super::influxdb_backend::Database::connect(connection_string)?;
                Ok(Database::InfluxDB(db))
            }
        }
    }

    /// 创建表 - 返回执行器
    pub fn create_table<T: WritableModel>(&self) -> CreateTableExecutor<'_, T> {
        match self {
            #[cfg(feature = "sqlite")]
            Database::Sqlite(db) => CreateTableExecutor::Sqlite(db.create_table::<T>()),
            #[cfg(feature = "postgresql")]
            Database::PostgreSQL(db) => CreateTableExecutor::PostgreSQL(db.create_table::<T>()),
            #[cfg(feature = "mysql")]
            Database::MySQL(db) => CreateTableExecutor::MySQL(db.create_table::<T>()),
            #[cfg(feature = "mssql")]
            Database::MSSQL(db) => CreateTableExecutor::MSSQL(db.create_table::<T>()),
            #[cfg(feature = "duckdb")]
            Database::DuckDB(db) => CreateTableExecutor::DuckDB(db.create_table::<T>()),
            #[cfg(feature = "clickhouse")]
            Database::ClickHouse(_) => CreateTableExecutor::Unsupported {
                backend: super::super::DbType::ClickHouse,
                feature: "CREATE TABLE without explicit ClickHouse engine settings",
                _marker: std::marker::PhantomData,
            },
            #[cfg(feature = "influxdb")]
            Database::InfluxDB(db) => {
                CreateTableExecutor::InfluxDB(db, std::marker::PhantomData)
            }
        }
    }

    /// 验证表结构
    ///
    /// 以 [`Capabilities::schema_introspection`] 为准:矩阵为 false 的后端
    /// (ClickHouse/InfluxDB)统一拒绝;QuestDB 为 true,走
    /// `table_columns()` 专用校验路径。
    pub async fn validate_table<T: WritableModel>(&self) -> crate::Result<()> {
        if !Capabilities::of(self.db_type()).schema_introspection {
            return Err(unsupported_feature(self.db_type(), "validate_table"));
        }
        match self {
            #[cfg(feature = "questdb")]
            Database::PostgreSQL(db) if db.db_type().is_questdb() => {
                let _ = db;
                self.validate_table_questdb::<T>().await
            }
            #[cfg(feature = "sqlite")]
            Database::Sqlite(db) => db.validate_table::<T>().await,
            #[cfg(feature = "postgresql")]
            Database::PostgreSQL(db) => db.validate_table::<T>().await,
            #[cfg(feature = "mysql")]
            Database::MySQL(db) => db.validate_table::<T>().await,
            #[cfg(feature = "mssql")]
            Database::MSSQL(db) => db.validate_table::<T>().await,
            #[cfg(feature = "duckdb")]
            Database::DuckDB(db) => db.validate_table::<T>().await,
            // 矩阵兜底:正常不可达(schema_introspection=false 已在上面拦截)。
            #[allow(unreachable_patterns)]
            _ => Err(unsupported_feature(self.db_type(), "validate_table")),
        }
    }

    /// Generate Rust model definitions from the database schema.
    ///
    /// 注意:db-first 实体生成不受 [`Capabilities::schema_introspection`] 门控
    /// (ClickHouse 的 db-first 可用而该字段为 false),InfluxDB/QuestDB 的
    /// 拒绝由本入口与 `postgresql_backend::db_first_tables` 分别硬编码。
    // schema 仅由 SQL 后端的 db_first_tables 分支消费(InfluxDB 提前拒绝)
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb",
            feature = "clickhouse"
        )),
        allow(unused_variables)
    )]
    pub async fn generate_entities(&self, schema: Option<&str>) -> crate::Result<String> {
        #[cfg(feature = "influxdb")]
        #[allow(irrefutable_let_patterns)]
        if let Database::InfluxDB(_) = self {
            return Err(unsupported_feature(
                super::super::DbType::InfluxDB,
                "generate_entities",
            ));
        }
        let tables = match self {
            #[cfg(feature = "sqlite")]
            Database::Sqlite(db) => db.db_first_tables(schema).await?,
            #[cfg(feature = "postgresql")]
            Database::PostgreSQL(db) => db.db_first_tables(schema).await?,
            #[cfg(feature = "mysql")]
            Database::MySQL(db) => db.db_first_tables(schema).await?,
            #[cfg(feature = "mssql")]
            Database::MSSQL(db) => db.db_first_tables(schema).await?,
            #[cfg(feature = "duckdb")]
            Database::DuckDB(db) => db.db_first_tables(schema).await?,
            #[cfg(feature = "clickhouse")]
            Database::ClickHouse(db) => db.db_first_tables(schema).await?,
            // 不可达:InfluxDB 已在函数开头提前报错,仅为 match 穷尽性保留
            #[cfg(feature = "influxdb")]
            Database::InfluxDB(_) => Vec::new(),
        };
        db_first::generate_entities(self.db_type(), &tables)
    }

    /// 插入记录 - 返回执行器
    pub fn insert<I: crate::model::Insertable>(&self, models: I) -> InsertExecutor<'_, I> {
        match self {
            #[cfg(feature = "sqlite")]
            Database::Sqlite(db) => InsertExecutor::Sqlite(db.insert::<I>(models)),
            #[cfg(feature = "postgresql")]
            Database::PostgreSQL(db) => InsertExecutor::PostgreSQL(db.insert::<I>(models)),
            #[cfg(feature = "mysql")]
            Database::MySQL(db) => InsertExecutor::MySQL(db.insert::<I>(models)),
            #[cfg(feature = "mssql")]
            Database::MSSQL(db) => InsertExecutor::MSSQL(db.insert::<I>(models)),
            #[cfg(feature = "duckdb")]
            Database::DuckDB(db) => InsertExecutor::DuckDB(db.insert::<I>(models)),
            #[cfg(feature = "clickhouse")]
            Database::ClickHouse(db) => {
                InsertExecutor::ClickHouse(db, models, None, std::marker::PhantomData)
            }
            #[cfg(feature = "influxdb")]
            Database::InfluxDB(db) => InsertExecutor::InfluxDB(
                db,
                models,
                None,
                std::marker::PhantomData,
            ),
        }
    }

    pub fn insert_partial<T: WritableModel + Send + Sync>(&self) -> InsertPartialExecutor<'_, T> {
        match self {
            #[cfg(feature = "sqlite")]
            Database::Sqlite(db) => {
                InsertPartialExecutor::Sqlite(db.insert_partial::<T>(), std::marker::PhantomData)
            }
            #[cfg(feature = "postgresql")]
            Database::PostgreSQL(db) => InsertPartialExecutor::PostgreSQL(db.insert_partial::<T>()),
            #[cfg(feature = "mysql")]
            Database::MySQL(db) => InsertPartialExecutor::MySQL(db.insert_partial::<T>()),
            #[cfg(feature = "mssql")]
            Database::MSSQL(db) => InsertPartialExecutor::MSSQL(db.insert_partial::<T>()),
            #[cfg(feature = "duckdb")]
            Database::DuckDB(db) => InsertPartialExecutor::DuckDB(db.insert_partial::<T>()),
            #[cfg(feature = "clickhouse")]
            Database::ClickHouse(_) => InsertPartialExecutor::Unsupported {
                backend: super::super::DbType::ClickHouse,
                feature: "partial Model insert on ClickHouse",
                _marker: std::marker::PhantomData,
            },
            #[cfg(feature = "influxdb")]
            Database::InfluxDB(_) => InsertPartialExecutor::Unsupported {
                backend: super::super::DbType::InfluxDB,
                feature: "insert_partial",
                _marker: std::marker::PhantomData,
            },
        }
    }

    // model 仅由本地后端分支消费(ClickHouse/InfluxDB 返回 Unsupported)
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb"
        )),
        allow(unused_variables)
    )]
    pub fn insert_model<T>(
        &self,
        model: impl crate::model::InsertModel<T>,
    ) -> InsertPartialExecutor<'_, T>
    where
        T: WritableModel + Send + Sync,
    {
        match self {
            #[cfg(feature = "sqlite")]
            Database::Sqlite(db) => {
                InsertPartialExecutor::Sqlite(db.insert_model::<T>(model), std::marker::PhantomData)
            }
            #[cfg(feature = "postgresql")]
            Database::PostgreSQL(db) => {
                InsertPartialExecutor::PostgreSQL(db.insert_model::<T>(model))
            }
            #[cfg(feature = "mysql")]
            Database::MySQL(db) => InsertPartialExecutor::MySQL(db.insert_model::<T>(model)),
            #[cfg(feature = "mssql")]
            Database::MSSQL(db) => InsertPartialExecutor::MSSQL(db.insert_model::<T>(model)),
            #[cfg(feature = "duckdb")]
            Database::DuckDB(db) => InsertPartialExecutor::DuckDB(db.insert_model::<T>(model)),
            #[cfg(feature = "clickhouse")]
            Database::ClickHouse(_) => InsertPartialExecutor::Unsupported {
                backend: super::super::DbType::ClickHouse,
                feature: "partial Model insert on ClickHouse",
                _marker: std::marker::PhantomData,
            },
            #[cfg(feature = "influxdb")]
            Database::InfluxDB(_) => InsertPartialExecutor::Unsupported {
                backend: super::super::DbType::InfluxDB,
                feature: "insert_model",
                _marker: std::marker::PhantomData,
            },
        }
    }

    pub fn insert_graph<'a, T>(&'a self, model: &'a mut T) -> InsertGraphExecutor<'a, T>
    where
        T: crate::model::GraphWritable,
    {
        InsertGraphExecutor { db: self, model }
    }

    /// 插入或更新记录 - 返回执行器
    ///
    /// 以 [`Capabilities::insert_conflict`] 为准:矩阵为 false 的后端
    /// (ClickHouse/InfluxDB/QuestDB)统一拒绝;QuestDB 复用 PostgreSQL 连接,
    /// 按运行时 `db_type` 判定,不能按 `Database` 枚举变体判定。
    // models 仅由本地后端分支消费(矩阵拒绝路径不使用)
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb"
        )),
        allow(unused_variables)
    )]
    pub fn insert_or_update<I: crate::model::Insertable>(
        &self,
        models: I,
    ) -> InsertOrUpdateExecutor<'_, I> {
        if !Capabilities::of(self.db_type()).insert_conflict {
            return InsertOrUpdateExecutor::Unsupported {
                backend: self.db_type(),
                feature: "insert conflict handling",
                _marker: std::marker::PhantomData,
            };
        }
        match self {
            #[cfg(feature = "sqlite")]
            Database::Sqlite(db) => {
                InsertOrUpdateExecutor::Sqlite(db.insert_or_update::<I>(models))
            }
            #[cfg(feature = "postgresql")]
            Database::PostgreSQL(db) => {
                InsertOrUpdateExecutor::PostgreSQL(db.insert_or_update::<I>(models))
            }
            #[cfg(feature = "mysql")]
            Database::MySQL(db) => InsertOrUpdateExecutor::MySQL(db.insert_or_update::<I>(models)),
            #[cfg(feature = "mssql")]
            Database::MSSQL(db) => InsertOrUpdateExecutor::MSSQL(db.insert_or_update::<I>(models)),
            #[cfg(feature = "duckdb")]
            Database::DuckDB(db) => {
                InsertOrUpdateExecutor::DuckDB(db.insert_or_update::<I>(models))
            }
            // 矩阵兜底:正常不可达(insert_conflict=false 已在上面拦截)。
            #[allow(unreachable_patterns)]
            _ => InsertOrUpdateExecutor::Unsupported {
                backend: self.db_type(),
                feature: "insert conflict handling",
                _marker: std::marker::PhantomData,
            },
        }
    }

    pub fn upsert<I: crate::model::Insertable>(&self, models: I) -> InsertOrUpdateExecutor<'_, I> {
        self.insert_or_update(models)
    }

    /// 插入或忽略记录 - 返回执行器(存在重复主键时忽略)
    ///
    /// 以 [`Capabilities::insert_ignore`] 为准:矩阵为 false 的后端
    /// (ClickHouse/InfluxDB/QuestDB)统一拒绝,QuestDB 按运行时 `db_type` 判定。
    // models 仅由本地后端分支消费(矩阵拒绝路径不使用)
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb"
        )),
        allow(unused_variables)
    )]
    pub fn insert_or_ignore<I: crate::model::Insertable>(
        &self,
        models: I,
    ) -> InsertOrIgnoreExecutor<'_, I> {
        if !Capabilities::of(self.db_type()).insert_ignore {
            return InsertOrIgnoreExecutor::Unsupported {
                backend: self.db_type(),
                feature: "insert ignore",
                _marker: std::marker::PhantomData,
            };
        }
        match self {
            #[cfg(feature = "sqlite")]
            Database::Sqlite(db) => {
                InsertOrIgnoreExecutor::Sqlite(db.insert_or_ignore::<I>(models))
            }
            #[cfg(feature = "postgresql")]
            Database::PostgreSQL(db) => {
                InsertOrIgnoreExecutor::PostgreSQL(db.insert_or_ignore::<I>(models))
            }
            #[cfg(feature = "mysql")]
            Database::MySQL(db) => InsertOrIgnoreExecutor::MySQL(db.insert_or_ignore::<I>(models)),
            #[cfg(feature = "mssql")]
            Database::MSSQL(db) => InsertOrIgnoreExecutor::MSSQL(db.insert_or_ignore::<I>(models)),
            #[cfg(feature = "duckdb")]
            Database::DuckDB(db) => {
                InsertOrIgnoreExecutor::DuckDB(db.insert_or_ignore::<I>(models))
            }
            // 矩阵兜底:正常不可达(insert_ignore=false 已在上面拦截)。
            #[allow(unreachable_patterns)]
            _ => InsertOrIgnoreExecutor::Unsupported {
                backend: self.db_type(),
                feature: "insert ignore",
                _marker: std::marker::PhantomData,
            },
        }
    }

    pub fn batch<'a, B>(&'a self, batch: B) -> BatchFuture<'a, B>
    where
        B: BatchQueries<'a>,
    {
        BatchFuture::new(batch)
    }

    pub fn batch_many<'a, I, Q>(&'a self, queries: I) -> BatchManyFuture<'a, Q>
    where
        I: IntoIterator<Item = Q>,
        Q: BatchQuery<'a>,
    {
        BatchManyFuture::new(queries)
    }

    /// 根据主键查找单条记录
    /// 支持单主键和复合主键
    /// ```ignore
    /// // 单主键
    /// let user: Option<User> = db.find_by_id::<User>(1).await?;
    /// // 复合主键
    /// let record: Option<OrderItem> = db.find_by_id::<OrderItem>((1, 2)).await?;
    /// ```
    pub async fn find_by_id<T: Model + 'static + std::marker::Send + std::marker::Sync>(
        &self,
        key: impl crate::model::PrimaryKey,
    ) -> crate::Result<Option<T>> {
        find_by_id_with_executor(self.select::<T>(), key).await
    }

    /// 查找单个模型的关联对象。
    pub async fn find_related<T, S>(
        &self,
        owner: &T,
        relation: S,
    ) -> crate::Result<Vec<S::Target>>
    where
        T: Model + 'static + std::marker::Send + std::marker::Sync,
        S: RelationSelection<T>,
        for<'b> S: RelationNestedLoader<'b, T> + std::marker::Send + std::marker::Sync,
        S::Target: std::marker::Send + std::marker::Sync,
        S::Via: std::marker::Send + std::marker::Sync,
    {
        find_related_with_executor(&self.select::<T>(), owner, &relation).await
    }

    /// 批量预加载关联对象,避免循环查询产生 N+1。
    pub async fn preload<T, S>(
        &self,
        owners: &mut [T],
        relation: S,
    ) -> crate::Result<()>
    where
        T: Model + 'static + std::marker::Send + std::marker::Sync,
        S: RelationSelection<T>,
        for<'b> S: RelationNestedLoader<'b, T> + std::marker::Send + std::marker::Sync,
        S::Target: std::marker::Send + std::marker::Sync,
        S::Via: std::marker::Send + std::marker::Sync,
    {
        preload_with_executor(&self.select::<T>(), owners, relation).await
    }

    /// 创建 Select 查询执行器
    pub fn select<T: Model>(&self) -> SelectExecutor<'_, T> {
        match self {
            #[cfg(feature = "sqlite")]
            Database::Sqlite(db) => SelectExecutor::Sqlite(db.select::<T>()),
            #[cfg(feature = "postgresql")]
            Database::PostgreSQL(db) => SelectExecutor::PostgreSQL(db.select::<T>()),
            #[cfg(feature = "mysql")]
            Database::MySQL(db) => SelectExecutor::MySQL(db.select::<T>()),
            #[cfg(feature = "mssql")]
            Database::MSSQL(db) => SelectExecutor::MSSQL(db.select::<T>()),
            #[cfg(feature = "duckdb")]
            Database::DuckDB(db) => SelectExecutor::DuckDB(db.select::<T>()),
            #[cfg(feature = "clickhouse")]
            Database::ClickHouse(db) => {
                SelectExecutor::ClickHouse(
                    ClickHouseSelectBackend::ClickHouse(db),
                    crate::query::builder::Select::default(),
                )
            }
            #[cfg(feature = "influxdb")]
            Database::InfluxDB(db) => SelectExecutor::ClickHouse(
                ClickHouseSelectBackend::Influx(db),
                crate::query::builder::Select::default(),
            ),
        }
    }

    pub fn scope(&self) -> DatabaseScope<'_> {
        DatabaseScope {
            db: self,
            context_filters: Vec::new(),
        }
    }

    pub fn from_derived<R: Model>(
        &self,
        derived: DerivedSelect<R>,
    ) -> DerivedTableSelectExecutor<'_, R> {
        DerivedTableSelectExecutor {
            db: self,
            select: crate::query::builder::from_derived(derived),
        }
    }

    /// 执行 UNION / UNION ALL / INTERSECT / EXCEPT 集合查询。
    ///
    /// ```ignore
    /// let union = Select::new()
    ///     .filter(|p| p.age.gt(30))
    ///     .union(Select::new().filter(|p| p.name.like("%admin%")));
    /// let rows: Vec<User> = db.select_union(union).collect().await?;
    /// ```
    pub fn select_union<T: Model>(
        &self,
        union: crate::query::builder::UnionSelect<T>,
    ) -> UnionSelectExecutor<'_, T> {
        UnionSelectExecutor { db: self, select: union }
    }

    /// 创建分组聚合查询执行器
    pub fn select_column<T: Model, V>(&self) -> ProjectionSelectExecutor<'_, T, V> {
        match self {
            #[cfg(feature = "sqlite")]
            Database::Sqlite(db) => {
                ProjectionSelectExecutor::Sqlite(db.select_column::<T, V>())
            }
            #[cfg(feature = "postgresql")]
            Database::PostgreSQL(db) => {
                ProjectionSelectExecutor::PostgreSQL(db.select_column::<T, V>())
            }
            #[cfg(feature = "mysql")]
            Database::MySQL(db) => ProjectionSelectExecutor::MySQL(db.select_column::<T, V>()),
            #[cfg(feature = "mssql")]
            Database::MSSQL(db) => ProjectionSelectExecutor::MSSQL(db.select_column::<T, V>()),
            #[cfg(feature = "duckdb")]
            Database::DuckDB(db) => ProjectionSelectExecutor::DuckDB(db.select_column::<T, V>()),
            #[cfg(feature = "clickhouse")]
            Database::ClickHouse(db) => match clickhouse_projection_gate(
                super::super::DbType::ClickHouse,
            ) {
                None => ProjectionSelectExecutor::ClickHouse(db, ProjectionSelect::new()),
                Some(feature) => ProjectionSelectExecutor::Unsupported {
                    backend: super::super::DbType::ClickHouse,
                    feature,
                    _marker: std::marker::PhantomData,
                },
            },
            #[cfg(feature = "influxdb")]
            Database::InfluxDB(_) => ProjectionSelectExecutor::Unsupported {
                backend: super::super::DbType::InfluxDB,
                feature: clickhouse_projection_gate(super::super::DbType::InfluxDB)
                    .unwrap_or("GROUP BY aggregation"),
                _marker: std::marker::PhantomData,
            },
        }
    }

    /// 创建 Delete 执行器
    ///
    /// 以 [`Capabilities::row_delete`] 为准:矩阵为 false 的后端
    /// (ClickHouse/InfluxDB/QuestDB)统一拒绝;QuestDB 复用 PostgreSQL 连接,
    /// 按运行时 `db_type` 判定,不能按 `Database` 枚举变体判定。
    pub fn delete<T: WritableModel>(&self) -> DeleteExecutor<'_, T> {
        if !Capabilities::of(self.db_type()).row_delete {
            return DeleteExecutor::Unsupported {
                backend: self.db_type(),
                feature: "row delete",
                _marker: std::marker::PhantomData,
            };
        }
        match self {
            #[cfg(feature = "sqlite")]
            Database::Sqlite(db) => {
                DeleteExecutor::Sqlite(db.delete::<T>(), std::marker::PhantomData)
            }
            #[cfg(feature = "postgresql")]
            Database::PostgreSQL(db) => DeleteExecutor::PostgreSQL(db.delete::<T>()),
            #[cfg(feature = "mysql")]
            Database::MySQL(db) => DeleteExecutor::MySQL(db.delete::<T>()),
            #[cfg(feature = "mssql")]
            Database::MSSQL(db) => DeleteExecutor::MSSQL(db.delete::<T>()),
            #[cfg(feature = "duckdb")]
            Database::DuckDB(db) => DeleteExecutor::DuckDB(db.delete::<T>()),
            // 矩阵兜底:正常不可达(row_delete=false 已在上面拦截)。
            #[allow(unreachable_patterns)]
            _ => DeleteExecutor::Unsupported {
                backend: self.db_type(),
                feature: "row delete",
                _marker: std::marker::PhantomData,
            },
        }
    }

    /// 创建按块删除执行器(时序数据整块清理,各后端语义见各执行器文档)
    ///
    /// 不做矩阵门控:[`Capabilities::block_delete`] 当前对所有后端为 true
    /// (ClickHouse/InfluxDB 走原生块删除,QuestDB 走 `DROP PARTITION`,
    /// 其余 OLTP 后端回退为对齐时间边界的行删除);该字段保留为未来新增
    /// 后端的统一门控入口。
    pub fn delete_blocks<T: WritableModel>(&self) -> BlockDeleteExecutor<'_, T> {
        match self {
            #[cfg(feature = "sqlite")]
            Database::Sqlite(db) => BlockDeleteExecutor::fallback(
                super::super::DbType::Sqlite,
                DeleteExecutor::Sqlite(db.delete::<T>(), std::marker::PhantomData),
            ),
            #[cfg(feature = "postgresql")]
            Database::PostgreSQL(db) => BlockDeleteExecutor::PostgreSQL(db.delete_blocks::<T>()),
            #[cfg(feature = "mysql")]
            Database::MySQL(db) => BlockDeleteExecutor::fallback(
                super::super::DbType::MySQL,
                DeleteExecutor::MySQL(db.delete::<T>()),
            ),
            #[cfg(feature = "mssql")]
            Database::MSSQL(db) => BlockDeleteExecutor::fallback(
                super::super::DbType::MSSQL,
                DeleteExecutor::MSSQL(db.delete::<T>()),
            ),
            #[cfg(feature = "duckdb")]
            Database::DuckDB(db) => BlockDeleteExecutor::fallback(
                super::super::DbType::DuckDB,
                DeleteExecutor::DuckDB(db.delete::<T>()),
            ),
            #[cfg(feature = "clickhouse")]
            Database::ClickHouse(db) => {
                BlockDeleteExecutor::ClickHouse(clickhouse_backend::BlockDeleteExecutor::new(db))
            }
            #[cfg(feature = "influxdb")]
            Database::InfluxDB(db) => {
                BlockDeleteExecutor::InfluxDB(influxdb_backend::BlockDeleteExecutor::new(db))
            }
        }
    }

    /// 创建 Update 执行器
    pub fn update<T: WritableModel>(&self) -> UpdateExecutor<'_, T> {
        match self {
            #[cfg(feature = "sqlite")]
            Database::Sqlite(db) => {
                UpdateExecutor::Sqlite(db.update::<T>(), std::marker::PhantomData)
            }
            #[cfg(feature = "postgresql")]
            Database::PostgreSQL(db) => UpdateExecutor::PostgreSQL(db.update::<T>()),
            #[cfg(feature = "mysql")]
            Database::MySQL(db) => UpdateExecutor::MySQL(db.update::<T>()),
            #[cfg(feature = "mssql")]
            Database::MSSQL(db) => UpdateExecutor::MSSQL(db.update::<T>()),
            #[cfg(feature = "duckdb")]
            Database::DuckDB(db) => UpdateExecutor::DuckDB(db.update::<T>()),
            #[cfg(feature = "clickhouse")]
            Database::ClickHouse(_) => UpdateExecutor::Unsupported {
                backend: super::super::DbType::ClickHouse,
                feature: "row update on ClickHouse; use execute_sql",
                _marker: std::marker::PhantomData,
            },
            #[cfg(feature = "influxdb")]
            Database::InfluxDB(_) => UpdateExecutor::Unsupported {
                backend: super::super::DbType::InfluxDB,
                feature: "row update",
                _marker: std::marker::PhantomData,
            },
        }
    }

    pub fn save<'a, T: WritableModel + crate::model::GraphWritable>(
        &'a self,
        model: &'a mut Tracked<T>,
    ) -> SaveExecutor<'a, T> {
        SaveExecutor {
            conn: SaveConn::Db(self),
            model,
        }
    }

    pub fn update_graph<'a, T>(&'a self, model: &'a mut T) -> UpdateGraphExecutor<'a, T>
    where
        T: crate::model::GraphWritable,
    {
        UpdateGraphExecutor { db: self, model }
    }

    /// 创建 Related 查询执行器(关联查询)
    pub fn from<T: Model + 'static, R: Model>(&self) -> RelatedSelectExecutor<'_, T, R> {
        match self {
            #[cfg(feature = "sqlite")]
            Database::Sqlite(db) => {
                RelatedSelectExecutor::Sqlite(db.related::<T, R>(), std::marker::PhantomData)
            }
            #[cfg(feature = "postgresql")]
            Database::PostgreSQL(db) => RelatedSelectExecutor::PostgreSQL(db.related::<T, R>()),
            #[cfg(feature = "mysql")]
            Database::MySQL(db) => RelatedSelectExecutor::MySQL(db.related::<T, R>()),
            #[cfg(feature = "mssql")]
            Database::MSSQL(db) => RelatedSelectExecutor::MSSQL(db.related::<T, R>()),
            #[cfg(feature = "duckdb")]
            Database::DuckDB(db) => RelatedSelectExecutor::DuckDB(db.related::<T, R>()),
            #[cfg(feature = "clickhouse")]
            Database::ClickHouse(_) => RelatedSelectExecutor::Unsupported {
                backend: super::super::DbType::ClickHouse,
                feature: "related (multi-table) select",
                _marker: std::marker::PhantomData,
            },
            #[cfg(feature = "influxdb")]
            Database::InfluxDB(_) => RelatedSelectExecutor::Unsupported {
                backend: super::super::DbType::InfluxDB,
                feature: "relation select",
                _marker: std::marker::PhantomData,
            },
        }
    }

    /// 开始事务
    ///
    /// 以 [`Capabilities::of`] 声明的事务能力为准:`transactions: false`
    /// 的后端(QuestDB/ClickHouse/InfluxDB)在此直接返回
    /// `UnsupportedFeature`,而不是透传底层协议的伪事务。
    pub async fn begin(&self) -> crate::Result<Transaction<'_>> {
        if !Capabilities::of(self.db_type()).transactions {
            return Err(unsupported_feature(self.db_type(), "transactions"));
        }
        match self {
            #[cfg(feature = "sqlite")]
            Database::Sqlite(db) => {
                let txn = db.begin().await?;
                Ok(Transaction::Sqlite(txn))
            }
            #[cfg(feature = "postgresql")]
            Database::PostgreSQL(db) => {
                let txn = db.begin().await?;
                Ok(Transaction::PostgreSQL(txn))
            }
            #[cfg(feature = "mysql")]
            Database::MySQL(db) => {
                let txn = db.begin().await?;
                Ok(Transaction::MySQL(txn))
            }
            #[cfg(feature = "mssql")]
            Database::MSSQL(db) => {
                let txn = db.begin().await?;
                Ok(Transaction::MSSQL(txn))
            }
            #[cfg(feature = "duckdb")]
            Database::DuckDB(db) => {
                let txn = db.begin().await?;
                Ok(Transaction::DuckDB(txn))
            }
            // 矩阵兜底:正常不可达(transactions=false 已在上面拦截)。
            #[allow(unreachable_patterns)]
            _ => Err(unsupported_feature(self.db_type(), "transactions")),
        }
    }

    pub async fn transaction<R, F>(&self, f: F) -> crate::Result<R>
    where
        F: for<'tx> FnOnce(&'tx mut Transaction<'_>) -> TransactionFuture<'tx, R>,
    {
        self.transaction_opts(TransactionOptions::new(), f).await
    }

    pub async fn transaction_opts<R, F>(
        &self,
        options: TransactionOptions,
        f: F,
    ) -> crate::Result<R>
    where
        F: for<'tx> FnOnce(&'tx mut Transaction<'_>) -> TransactionFuture<'tx, R>,
    {
        // 选项必须在 begin 阶段按后端语义下发(MySQL 的 SET TRANSACTION
        // 只作用于"下一个事务",begin 之后设置无效);收尾(提交/回滚)
        // 与池层共用 run_txn_closure。
        let txn = self.begin_opts(options).await?;
        run_txn_closure(txn, f).await
    }

    async fn begin_opts(&self, options: TransactionOptions) -> crate::Result<Transaction<'_>> {
        // MySQL 的选项必须在 BEGIN 前下发(begin_with_opts),其余后端
        // 走"先 BEGIN 再应用选项、失败回滚"的公共路径。
        #[cfg(feature = "mysql")]
        // mysql-only 组合下该枚举仅剩一个变体,if let 不可反驳属预期
        #[allow(irrefutable_let_patterns)]
        if let Database::MySQL(db) = self {
            let txn = db.begin_with_opts(options).await?;
            return Ok(Transaction::MySQL(txn));
        }
        apply_transaction_options_or_rollback(self.begin().await?, options).await
    }

    /// 删除表 - 返回执行器
    pub fn drop_table<T: WritableModel>(&self) -> DropTableExecutor<'_, T> {
        match self {
            #[cfg(feature = "sqlite")]
            Database::Sqlite(db) => DropTableExecutor::Sqlite(db.drop_table::<T>()),
            #[cfg(feature = "postgresql")]
            Database::PostgreSQL(db) => DropTableExecutor::PostgreSQL(db.drop_table::<T>()),
            #[cfg(feature = "mysql")]
            Database::MySQL(db) => DropTableExecutor::MySQL(db.drop_table::<T>()),
            #[cfg(feature = "mssql")]
            Database::MSSQL(db) => DropTableExecutor::MSSQL(db.drop_table::<T>()),
            #[cfg(feature = "duckdb")]
            Database::DuckDB(db) => DropTableExecutor::DuckDB(db.drop_table::<T>()),
            #[cfg(feature = "clickhouse")]
            Database::ClickHouse(db) => DropTableExecutor::ClickHouse(db, std::marker::PhantomData),
            #[cfg(feature = "influxdb")]
            Database::InfluxDB(db) => {
                DropTableExecutor::InfluxDB(db, std::marker::PhantomData)
            }
        }
    }

    /// 清空表数据 - 返回执行器(`TRUNCATE TABLE`)
    ///
    /// 以 [`Capabilities::truncate`] 为准:QuestDB 不支持行级 DELETE,
    /// 这是清空表数据的唯一受支持手段(QuestDB 复用 PostgreSQL 连接,
    /// 按运行时 `db_type` 判定,仍走 PostgreSQL 执行器分支);
    /// MySQL/MSSQL/DuckDB 原生支持;SQLite 无 TRUNCATE 语法(保持 false)。
    pub fn truncate_table<T: WritableModel>(&self) -> TruncateTableExecutor<'_, T> {
        if !Capabilities::of(self.db_type()).truncate {
            return TruncateTableExecutor::Unsupported {
                backend: self.db_type(),
                feature: "truncate_table",
                _marker: std::marker::PhantomData,
            };
        }
        match self {
            #[cfg(feature = "postgresql")]
            Database::PostgreSQL(db) => {
                TruncateTableExecutor::PostgreSQL(db.truncate_table::<T>())
            }
            #[cfg(feature = "mysql")]
            Database::MySQL(db) => TruncateTableExecutor::MySQL(db.truncate_table::<T>()),
            #[cfg(feature = "mssql")]
            Database::MSSQL(db) => TruncateTableExecutor::MSSQL(db.truncate_table::<T>()),
            #[cfg(feature = "duckdb")]
            Database::DuckDB(db) => TruncateTableExecutor::DuckDB(db.truncate_table::<T>()),
            // 矩阵兜底:正常不可达(truncate=false 已在上面拦截),
            // 保留防御性拒绝以避免矩阵漂移时 panic。
            #[allow(unreachable_patterns)]
            _ => TruncateTableExecutor::Unsupported {
                backend: self.db_type(),
                feature: "truncate_table",
                _marker: std::marker::PhantomData,
            },
        }
    }

    pub fn select_sql<T>(&self, sql: impl IntoRawSql) -> RawSelectExecutor<'_, T> {
        RawSelectExecutor::from_conn(ConnRef::Db(self), sql.into_raw_sql())
    }

    /// 执行原生非查询 SQL 并返回影响的行数
    ///
    /// 注意:ClickHouse 与 InfluxDB 的执行通道(HTTP)不报告 affected rows,
    /// 这两个后端恒返回 `Ok(0)`——即使语句实际修改了大量数据。调用方不能
    /// 以返回值 0 区分"未影响任何行"与"后端不统计行数";需要精确行数时
    /// 应改用 `SELECT count()`(前后各查一次)或选择支持行数统计的后端。
    pub async fn execute_sql(&self, sql: impl IntoRawSql) -> crate::Result<u64> {
        // L21:Database / 事务 / 池连接三路径共用一份后端分派。
        exec_raw_sql_on(ConnRefMut::Db(self), sql.into_raw_sql()).await
    }

    /// Count rows in a table using backend-specific identifier quoting.
    pub async fn table_row_count(&self, table_name: &str) -> crate::Result<u64> {
        let sql = format!(
            "SELECT COUNT(*) FROM {}",
            common_helpers::quote_table_name_with_schema(self.db_type(), table_name)
        );
        let rows = self.select_sql::<i64>(sql).collect::<Vec<i64>>().await?;
        Ok(rows.into_iter().next().unwrap_or(0).max(0) as u64)
    }

    /// 创建连接池
    #[cfg(any(
        feature = "sqlite",
        feature = "postgresql",
        feature = "mysql",
        feature = "mssql",
        feature = "duckdb",
        feature = "clickhouse"
    ))]
    pub fn create_pool(
        db_type: super::super::DbType,
        connection_string: &str,
    ) -> super::connection_pool::PoolBuilder {
        super::connection_pool::PoolBuilder::new(db_type, connection_string)
    }
}

impl super::DbExecutor for Database {
    fn select<T: Model>(&self) -> SelectExecutor<'_, T> {
        Database::select::<T>(self)
    }

    fn select_column<T: Model, V>(&self) -> ProjectionSelectExecutor<'_, T, V> {
        Database::select_column::<T, V>(self)
    }
}

impl<'a, R: Model> DerivedTableSelectExecutor<'a, R> {
    pub fn filter<F, W>(mut self, f: F) -> Self
    where
        F: FnOnce(R::Where) -> W,
        W: Into<WhereExpr>,
    {
        self.select = self.select.filter(f);
        self
    }

    pub fn order_by<F, O>(mut self, f: F) -> Self
    where
        F: FnOnce(R::Where) -> O,
        O: Into<crate::OrderBy>,
    {
        self.select = self.select.order_by(f);
        self
    }

    pub fn order_by_desc<F, O>(mut self, f: F) -> Self
    where
        F: FnOnce(R::Where) -> O,
        O: Into<crate::OrderBy>,
    {
        self.select = self.select.order_by_desc(f);
        self
    }

    pub fn range<RR: Into<crate::query::builder::RangeBounds>>(mut self, range: RR) -> Self {
        self.select = self.select.range(range);
        self
    }

    pub fn collect<C>(self) -> DerivedTableCollectFuture<'a, R, C>
    where
        R: crate::model::FromRowValues + 'static,
        C: FromIterator<R> + 'static,
    {
        DerivedTableCollectFuture {
            db: self.db,
            select: self.select,
            _marker: std::marker::PhantomData,
        }
    }

    pub fn to_sql(&self) -> crate::Result<SqlStatement> {
        let db_type = self.db.db_type();
        #[cfg(feature = "postgresql")]
        if matches!(db_type, crate::DbType::PostgreSQL) {
            let (sql, params, rust_types) =
                self.select.try_to_sql_with_params_and_types(db_type)?;
            return Ok(SqlStatement::batch(
                db_type,
                vec![super::SingleSqlStatement::new(sql, params).with_param_rust_types(rust_types)],
            ));
        }

        let (sql, params) = self.select.try_to_sql_with_params(db_type)?;
        Ok(SqlStatement::single(db_type, sql, params))
    }
}

pub struct DerivedTableCollectFuture<'a, R: Model, C> {
    db: &'a Database,
    // select 仅由 SQL 后端分支消费;influxdb-only 组合下恒为 Unsupported
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb",
            feature = "clickhouse"
        )),
        allow(dead_code)
    )]
    select: DerivedTableSelect<R>,
    _marker: std::marker::PhantomData<C>,
}

impl<'a, R, C> std::future::IntoFuture for DerivedTableCollectFuture<'a, R, C>
where
    R: Model + crate::model::FromRowValues + 'static + std::marker::Send,
    C: FromIterator<R> + 'static,
{
    type Output = crate::Result<C>;
    type IntoFuture =
        std::pin::Pin<Box<dyn std::future::Future<Output = Self::Output> + Send + 'a>>;

    // db_type/sql/params 仅由 SQL 后端分支消费;influxdb-only 组合下无消费方属预期
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb",
            feature = "clickhouse"
        )),
        allow(unused_variables)
    )]
    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let db_type = self.db.db_type();
            match self.db {
                #[cfg(feature = "sqlite")]
                Database::Sqlite(db) => {
                    let (sql, params) = self.select.try_to_sql_with_params(db_type)?;
                    db.select_raw::<R, C>(&sql, params).await
                }
                #[cfg(feature = "postgresql")]
                Database::PostgreSQL(db) => {
                    let (sql, params, rust_types) =
                        self.select.try_to_sql_with_params_and_types(db_type)?;
                    db.select_raw_with_types::<R, C>(&sql, params, rust_types)
                        .await
                }
                #[cfg(feature = "mysql")]
                Database::MySQL(db) => {
                    let (sql, params) = self.select.try_to_sql_with_params(db_type)?;
                    db.select_raw::<R, C>(&sql, params).await
                }
                #[cfg(feature = "mssql")]
                Database::MSSQL(db) => {
                    let (sql, params) = self.select.try_to_sql_with_params(db_type)?;
                    db.select_raw::<R, C>(&sql, params).await
                }
                #[cfg(feature = "duckdb")]
                Database::DuckDB(db) => {
                    let (sql, params) = self.select.try_to_sql_with_params(db_type)?;
                    db.select_raw::<R, C>(&sql, params).await
                }
                #[cfg(feature = "clickhouse")]
            Database::ClickHouse(db) => {
                let (sql, params) = self.select.try_to_sql_with_params(db_type)?;
                    let rows = db
                        .select_values(RawSql::new(sql).with_params(params), R::row_columns())
                        .await?;
                    rows.into_iter()
                        .map(|values| <R as crate::model::FromRowValues>::from_row_values(&values))
                        .collect::<crate::Result<C>>()
                }
                #[cfg(feature = "influxdb")]
                Database::InfluxDB(_) => Err(unsupported_feature(
                    super::super::DbType::InfluxDB,
                    "derived table select",
                )),
            }
        })
    }
}

/// UNION/INTERSECT/EXCEPT 集合查询执行器(P1-1)。
///
/// SQL 由 [`crate::query::builder::UnionSelect::try_to_sql_with_params`] 生成:操作数以括号包装,
/// 避免操作数自带 ORDER BY/LIMIT 时产生非法 SQL;MSSQL 例外——T-SQL
/// 不支持括号化操作数,按非括号形态拼接。
pub struct UnionSelectExecutor<'a, T: Model> {
    db: &'a Database,
    select: crate::query::builder::UnionSelect<T>,
}

impl<'a, T: Model> UnionSelectExecutor<'a, T> {
    pub fn to_sql(&self) -> crate::Result<SqlStatement> {
        let db_type = self.db.db_type();
        // MSSQL 的 T-SQL 不支持括号化集合操作数,按非括号形态拼接
        #[cfg(feature = "mssql")]
        let (sql, params) = if db_type == super::super::DbType::MSSQL {
            self.select.to_sql_with_params_unparenthesized(db_type)
        } else {
            self.select.try_to_sql_with_params(db_type)?
        };
        #[cfg(not(feature = "mssql"))]
        let (sql, params) = self.select.try_to_sql_with_params(db_type)?;
        Ok(SqlStatement::single(db_type, sql, params))
    }

    pub fn collect<C>(self) -> UnionCollectFuture<'a, T, C>
    where
        T: crate::model::FromRowValues + 'static,
        C: FromIterator<T> + 'static,
    {
        UnionCollectFuture {
            db: self.db,
            select: self.select,
            _marker: std::marker::PhantomData,
        }
    }

    /// 取第一行(等价于 `collect::<Vec<_>>()` 后取首元素)。
    pub async fn first(self) -> crate::Result<Option<T>>
    where
        T: crate::model::FromRowValues + 'static + Send,
    {
        Ok(self
            .collect::<Vec<T>>()
            .await?
            .into_iter()
            .next())
    }
}

pub struct UnionCollectFuture<'a, T: Model, C> {
    db: &'a Database,
    select: crate::query::builder::UnionSelect<T>,
    _marker: std::marker::PhantomData<C>,
}

impl<'a, T, C> std::future::IntoFuture for UnionCollectFuture<'a, T, C>
where
    T: Model + crate::model::FromRowValues + 'static + std::marker::Send,
    C: FromIterator<T> + 'static,
{
    type Output = crate::Result<C>;
    type IntoFuture =
        std::pin::Pin<Box<dyn std::future::Future<Output = Self::Output> + Send + 'a>>;

    // sql/params 仅由 SQL 后端分支消费;influxdb-only 组合下无消费方属预期
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb",
            feature = "clickhouse"
        )),
        allow(unused_variables)
    )]
    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let db_type = self.db.db_type();
            // MSSQL 的 T-SQL 不支持括号化集合操作数
            #[cfg(feature = "mssql")]
            let (sql, params) = if db_type == super::super::DbType::MSSQL {
                self.select.to_sql_with_params_unparenthesized(db_type)
            } else {
                self.select.try_to_sql_with_params(db_type)?
            };
            #[cfg(not(feature = "mssql"))]
            let (sql, params) = self.select.try_to_sql_with_params(db_type)?;
            match self.db {
                #[cfg(feature = "sqlite")]
                Database::Sqlite(db) => db.select_raw::<T, C>(&sql, params).await,
                #[cfg(feature = "postgresql")]
                Database::PostgreSQL(db) => db.select_raw::<T, C>(&sql, params).await,
                #[cfg(feature = "mysql")]
                Database::MySQL(db) => db.select_raw::<T, C>(&sql, params).await,
                #[cfg(feature = "duckdb")]
                Database::DuckDB(db) => db.select_raw::<T, C>(&sql, params).await,
                #[cfg(feature = "mssql")]
                Database::MSSQL(db) => db.select_raw::<T, C>(&sql, params).await,
                #[cfg(feature = "clickhouse")]
                Database::ClickHouse(db) => {
                    let rows = db
                        .select_values(RawSql::new(sql).with_params(params), T::row_columns())
                        .await?;
                    rows.into_iter()
                        .map(|values| <T as crate::model::FromRowValues>::from_row_values(&values))
                        .collect::<crate::Result<C>>()
                }
                #[cfg(feature = "influxdb")]
                Database::InfluxDB(_) => Err(unsupported_feature(
                    super::super::DbType::InfluxDB,
                    "union select",
                )),
            }
        })
    }
}

/// 统一层内部连接句柄(R3):Database / Transaction / 池连接三条执行路径
/// 共用一份执行器实现的关键。
///
/// `Txn` 持共享引用:raw select 路径的后端 `select_raw` 均为 `&self` 接收器,
/// 且 `&Transaction` 的协变性允许把 `&'op Transaction<'a>` 收缩为
/// `&'op Transaction<'op>`,避免 `&'a mut Transaction<'a>` 的不变性陷阱。
/// 写路径(Save)需要 `&mut Transaction`,无法共享本句柄,见 [`SaveConn`]。
#[derive(Clone, Copy)]
pub(crate) enum ConnRef<'a> {
    Db(&'a Database),
    Txn(&'a Transaction<'a>),
    /// 池连接路径(`PooledConnection::select_sql`)。
    Pooled(&'a connection_pool::ConnectionWrapper),
}

/// 写路径连接句柄:与 [`ConnRef`] 同构,但事务变体持 `&mut Transaction`
/// ——后端事务 `exec_raw` 为 `&mut self` 接收器,共享引用无法调用;
/// 读路径(select_raw)无此需求,继续用 [`ConnRef`]。仅被
/// [`exec_raw_sql_on`] 消费。`'tx` 独立于引用生命周期 `'a`:`&mut T`
/// 对 `T` 不变,`&'a mut Transaction<'a>` 会阻断 `Transaction` 协变性
/// 允许的生命周期收缩(见 `Transaction::execute_sql`)。
pub(crate) enum ConnRefMut<'a, 'tx> {
    Db(&'a Database),
    Txn(&'a mut Transaction<'tx>),
    Pooled(&'a connection_pool::ConnectionWrapper),
}

/// 原生非查询 SQL 的公共分派(L21):[`Database::execute_sql`] /
/// `Transaction::execute_sql` / `PooledConnection::execute_sql` 三条路径
/// 共用一份后端 match(与 raw select 的 [`RawCollectFuture`] 三路合一
/// 先例同构)。ClickHouse/InfluxDB 的执行通道(HTTP)不报告 affected
/// rows,恒返回 `Ok(0)`。写路径:事务变体需 `&mut`,见 [`ConnRefMut`]。
pub(crate) async fn exec_raw_sql_on(
    conn: ConnRefMut<'_, '_>,
    sql: RawSql,
) -> crate::Result<u64> {
    match conn {
        #[cfg(feature = "sqlite")]
        ConnRefMut::Db(Database::Sqlite(db)) => {
            let (sql, params) = sql.render(super::super::DbType::Sqlite)?;
            db.exec_raw(&sql, params).await
        }
        #[cfg(feature = "sqlite")]
        ConnRefMut::Txn(Transaction::Sqlite(txn)) => {
            let (sql, params) = sql.render(super::super::DbType::Sqlite)?;
            txn.exec_raw(&sql, params).await
        }
        #[cfg(feature = "postgresql")]
        ConnRefMut::Db(Database::PostgreSQL(db)) => {
            let (sql, params) = sql.render(super::super::DbType::PostgreSQL)?;
            db.exec_raw(&sql, params).await
        }
        #[cfg(feature = "postgresql")]
        ConnRefMut::Txn(Transaction::PostgreSQL(txn)) => {
            let (sql, params) = sql.render(super::super::DbType::PostgreSQL)?;
            txn.exec_raw(&sql, params).await
        }
        #[cfg(feature = "mysql")]
        ConnRefMut::Db(Database::MySQL(db)) => {
            let (sql, params) = sql.render(super::super::DbType::MySQL)?;
            db.exec_raw(&sql, params).await
        }
        #[cfg(feature = "mysql")]
        ConnRefMut::Txn(Transaction::MySQL(txn)) => {
            let (sql, params) = sql.render(super::super::DbType::MySQL)?;
            txn.exec_raw(&sql, params).await
        }
        #[cfg(feature = "mssql")]
        ConnRefMut::Db(Database::MSSQL(db)) => {
            let (sql, params) = sql.render(super::super::DbType::MSSQL)?;
            db.exec_raw(&sql, params).await
        }
        #[cfg(feature = "mssql")]
        ConnRefMut::Txn(Transaction::MSSQL(txn)) => {
            let (sql, params) = sql.render(super::super::DbType::MSSQL)?;
            txn.exec_raw(&sql, params).await
        }
        #[cfg(feature = "duckdb")]
        ConnRefMut::Db(Database::DuckDB(db)) => {
            let (sql, params) = sql.render(super::super::DbType::DuckDB)?;
            db.exec_raw(&sql, params).await
        }
        #[cfg(feature = "duckdb")]
        ConnRefMut::Txn(Transaction::DuckDB(txn)) => {
            let (sql, params) = sql.render(super::super::DbType::DuckDB)?;
            txn.exec_raw(&sql, params).await
        }
        #[cfg(feature = "postgresql")]
        ConnRefMut::Pooled(connection_pool::ConnectionWrapper::PostgreSQL(db)) => {
            let (sql, params) = sql.render(super::super::DbType::PostgreSQL)?;
            db.exec_raw(&sql, params).await
        }
        #[cfg(feature = "mysql")]
        ConnRefMut::Pooled(connection_pool::ConnectionWrapper::MySQL(db)) => {
            let (sql, params) = sql.render(super::super::DbType::MySQL)?;
            db.exec_raw(&sql, params).await
        }
        #[cfg(feature = "mssql")]
        ConnRefMut::Pooled(connection_pool::ConnectionWrapper::MSSQL(db)) => {
            let (sql, params) = sql.render(super::super::DbType::MSSQL)?;
            db.exec_raw(&sql, params).await
        }
        #[cfg(feature = "duckdb")]
        ConnRefMut::Pooled(connection_pool::ConnectionWrapper::DuckDB(db)) => {
            let (sql, params) = sql.render(super::super::DbType::DuckDB)?;
            db.exec_raw(&sql, params).await
        }
        #[cfg(feature = "sqlite")]
        ConnRefMut::Pooled(connection_pool::ConnectionWrapper::Sqlite(db)) => {
            let (sql, params) = sql.render(super::super::DbType::Sqlite)?;
            db.exec_raw(&sql, params).await
        }
        #[cfg(feature = "clickhouse")]
        ConnRefMut::Db(Database::ClickHouse(db)) => {
            db.execute_sql(sql).await?;
            Ok(0)
        }
        #[cfg(feature = "clickhouse")]
        ConnRefMut::Pooled(connection_pool::ConnectionWrapper::ClickHouse(db)) => {
            db.execute_sql(sql).await?;
            Ok(0)
        }
        #[cfg(feature = "influxdb")]
        ConnRefMut::Db(Database::InfluxDB(db)) => {
            db.execute_sql(sql).await?;
            Ok(0)
        }
        #[cfg(feature = "influxdb")]
        ConnRefMut::Pooled(connection_pool::ConnectionWrapper::InfluxDB(db)) => {
            db.execute_sql(sql).await?;
            Ok(0)
        }
        // 事务路径不含 ClickHouse/InfluxDB(transactions: false),
        // 仅剩 Transaction 的哨兵变体,做 void 消除。
        ConnRefMut::Txn(Transaction::_Phantom(infallible, _)) => match *infallible {},
    }
}

pub struct RawSelectExecutor<'a, T> {
    conn: ConnRef<'a>,
    sql: RawSql,
    _marker: std::marker::PhantomData<T>,
}

impl<'a, T> RawSelectExecutor<'a, T> {
    pub(crate) fn from_conn(conn: ConnRef<'a>, sql: RawSql) -> Self {
        Self {
            conn,
            sql,
            _marker: std::marker::PhantomData,
        }
    }

    pub fn collect<C>(self) -> RawCollectFuture<'a, T, C>
    where
        T: crate::model::FromRowValues + 'static,
        C: FromIterator<T> + 'static,
    {
        RawCollectFuture {
            conn: self.conn,
            sql: self.sql,
            _marker: std::marker::PhantomData,
        }
    }
}

/// 旧事务 raw select 执行器名过渡别名(已合并为 [`RawSelectExecutor`],
/// 保留 re-export 以兼容现有导入路径;`'tx` 参数仅为兼容旧签名保留)。
#[deprecated(
    since = "0.2.12",
    note = "TransactionRawSelectExecutor 已合并为 RawSelectExecutor,请改用 RawSelectExecutor"
)]
pub type TransactionRawSelectExecutor<'a, 'tx, T> = RawSelectExecutor<'a, T>;

/// 旧池 raw select 执行器名过渡别名(已合并为 [`RawSelectExecutor`],
/// 保留 re-export 以兼容现有导入路径;`'pool` 参数仅为兼容旧签名保留)。
#[deprecated(
    since = "0.2.12",
    note = "PooledRawSelectExecutor 已合并为 RawSelectExecutor,请改用 RawSelectExecutor"
)]
pub type PooledRawSelectExecutor<'conn, 'pool, T> = RawSelectExecutor<'conn, T>;

pub struct RawCollectFuture<'a, T, C> {
    conn: ConnRef<'a>,
    sql: RawSql,
    _marker: std::marker::PhantomData<(T, C)>,
}

/// 旧事务 raw collect future 名过渡别名(已合并为 [`RawCollectFuture`])。
#[deprecated(
    since = "0.2.12",
    note = "TransactionRawCollectFuture 已合并为 RawCollectFuture,请改用 RawCollectFuture"
)]
pub type TransactionRawCollectFuture<'a, 'tx, T, C> = RawCollectFuture<'a, T, C>;

impl<'a, T, C> std::future::IntoFuture for RawCollectFuture<'a, T, C>
where
    T: crate::model::FromRowValues + 'static + std::marker::Send,
    C: FromIterator<T> + 'static,
{
    type Output = crate::Result<C>;
    type IntoFuture =
        std::pin::Pin<Box<dyn std::future::Future<Output = Self::Output> + Send + 'a>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            // Database / Transaction / 池连接三路径在此共用一份后端分派
            // (R3 合并;各路径的 render 与解码行为与合并前逐字一致)。
            match self.conn {
                #[cfg(feature = "sqlite")]
                ConnRef::Db(Database::Sqlite(db)) => {
                    let (sql, params) = self.sql.render(super::super::DbType::Sqlite)?;
                    db.select_raw::<T, C>(&sql, params).await
                }
                #[cfg(feature = "sqlite")]
                ConnRef::Txn(Transaction::Sqlite(txn)) => {
                    let (sql, params) = self.sql.render(super::super::DbType::Sqlite)?;
                    txn.select_raw::<T, C>(&sql, params).await
                }
                #[cfg(feature = "postgresql")]
                ConnRef::Db(Database::PostgreSQL(db)) => {
                    let (sql, params) = self.sql.render(super::super::DbType::PostgreSQL)?;
                    db.select_raw::<T, C>(&sql, params).await
                }
                #[cfg(feature = "postgresql")]
                ConnRef::Txn(Transaction::PostgreSQL(txn)) => {
                    let (sql, params) = self.sql.render(super::super::DbType::PostgreSQL)?;
                    txn.select_raw::<T, C>(&sql, params).await
                }
                #[cfg(feature = "mysql")]
                ConnRef::Db(Database::MySQL(db)) => {
                    let (sql, params) = self.sql.render(super::super::DbType::MySQL)?;
                    db.select_raw::<T, C>(&sql, params).await
                }
                #[cfg(feature = "mysql")]
                ConnRef::Txn(Transaction::MySQL(txn)) => {
                    let (sql, params) = self.sql.render(super::super::DbType::MySQL)?;
                    txn.select_raw::<T, C>(&sql, params).await
                }
                #[cfg(feature = "mssql")]
                ConnRef::Db(Database::MSSQL(db)) => {
                    let (sql, params) = self.sql.render(super::super::DbType::MSSQL)?;
                    db.select_raw::<T, C>(&sql, params).await
                }
                #[cfg(feature = "mssql")]
                ConnRef::Txn(Transaction::MSSQL(txn)) => {
                    let (sql, params) = self.sql.render(super::super::DbType::MSSQL)?;
                    txn.select_raw::<T, C>(&sql, params).await
                }
                #[cfg(feature = "duckdb")]
                ConnRef::Db(Database::DuckDB(db)) => {
                    let (sql, params) = self.sql.render(super::super::DbType::DuckDB)?;
                    db.select_raw::<T, C>(&sql, params).await
                }
                #[cfg(feature = "duckdb")]
                ConnRef::Txn(Transaction::DuckDB(txn)) => {
                    let (sql, params) = self.sql.render(super::super::DbType::DuckDB)?;
                    txn.select_raw::<T, C>(&sql, params).await
                }
                #[cfg(feature = "postgresql")]
                ConnRef::Pooled(connection_pool::ConnectionWrapper::PostgreSQL(db)) => {
                    let (sql, params) = self.sql.render(super::super::DbType::PostgreSQL)?;
                    db.select_raw::<T, C>(&sql, params).await
                }
                #[cfg(feature = "mysql")]
                ConnRef::Pooled(connection_pool::ConnectionWrapper::MySQL(db)) => {
                    let (sql, params) = self.sql.render(super::super::DbType::MySQL)?;
                    db.select_raw::<T, C>(&sql, params).await
                }
                #[cfg(feature = "mssql")]
                ConnRef::Pooled(connection_pool::ConnectionWrapper::MSSQL(db)) => {
                    let (sql, params) = self.sql.render(super::super::DbType::MSSQL)?;
                    db.select_raw::<T, C>(&sql, params).await
                }
                #[cfg(feature = "duckdb")]
                ConnRef::Pooled(connection_pool::ConnectionWrapper::DuckDB(db)) => {
                    let (sql, params) = self.sql.render(super::super::DbType::DuckDB)?;
                    db.select_raw::<T, C>(&sql, params).await
                }
                #[cfg(feature = "sqlite")]
                ConnRef::Pooled(connection_pool::ConnectionWrapper::Sqlite(db)) => {
                    let (sql, params) = self.sql.render(super::super::DbType::Sqlite)?;
                    db.select_raw::<T, C>(&sql, params).await
                }
                #[cfg(feature = "clickhouse")]
                ConnRef::Db(Database::ClickHouse(db)) => {
                    let (sql, params) = self.sql.render(super::super::DbType::ClickHouse)?;
                    let rows = db
                        .select_values(
                            crate::raw_sql::RawSql::new(sql).with_params(params),
                            <T as crate::model::FromRowValues>::row_columns(),
                        )
                        .await?;
                    rows.into_iter()
                        .map(|values| T::from_row_values(&values))
                        .collect::<crate::Result<C>>()
                }
                #[cfg(feature = "clickhouse")]
                ConnRef::Pooled(connection_pool::ConnectionWrapper::ClickHouse(db)) => {
                    let rows = db
                        .select_values(self.sql, <T as crate::model::FromRowValues>::row_columns())
                        .await?;
                    rows.into_iter()
                        .map(|values| T::from_row_values(&values))
                        .collect::<crate::Result<C>>()
                }
                #[cfg(feature = "influxdb")]
                ConnRef::Db(Database::InfluxDB(db)) => {
                    let rows = db
                        .select_values(
                            self.sql,
                            <T as crate::model::FromRowValues>::row_columns(),
                        )
                        .await?;
                    rows.into_iter()
                        .map(|values| T::from_row_values(&values))
                        .collect::<crate::Result<C>>()
                }
                #[cfg(feature = "influxdb")]
                ConnRef::Pooled(connection_pool::ConnectionWrapper::InfluxDB(db)) => {
                    let rows = db
                        .select_values(self.sql, <T as crate::model::FromRowValues>::row_columns())
                        .await?;
                    rows.into_iter()
                        .map(|values| T::from_row_values(&values))
                        .collect::<crate::Result<C>>()
                }
                // 事务路径不含 ClickHouse/InfluxDB(transactions: false),
                // 仅剩 Transaction 的哨兵变体,做 void 消除。
                ConnRef::Txn(Transaction::_Phantom(infallible, _)) => match *infallible {},
            }
        })
    }
}


/// 统一的 SelectExecutor 枚举
pub enum SelectExecutor<'a, T: Model> {
    #[cfg(feature = "sqlite")]
    Sqlite(sqlite_backend::SelectExecutor<'a, T>),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::SelectExecutor<'a, T>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::SelectExecutor<'a, T>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::SelectExecutor<'a, T>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::SelectExecutor<'a, T>),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    ClickHouse(crate::abstract_layer::common::unified::ClickHouseSelectBackend<'a>, crate::query::builder::Select<T>),
}

/// ClickHouse protocol backend handle; InfluxDB reuses it only as a hidden
/// unsupported placeholder so builder APIs remain compilable without a DB.
#[cfg(any(feature = "clickhouse", feature = "influxdb"))]
#[derive(Clone, Copy)]
pub enum ClickHouseSelectBackend<'a> {
    #[cfg(feature = "clickhouse")]
    ClickHouse(&'a clickhouse_backend::Database),
    #[cfg(feature = "influxdb")]
    #[doc(hidden)]
    Influx(&'a influxdb_backend::Database),
}

#[cfg(any(feature = "clickhouse", feature = "influxdb"))]
fn clickhouse_select_backend_db_type(
    db: ClickHouseSelectBackend<'_>,
) -> super::super::DbType {
    match db {
        #[cfg(feature = "clickhouse")]
        ClickHouseSelectBackend::ClickHouse(_) => super::super::DbType::ClickHouse,
        #[cfg(feature = "influxdb")]
        ClickHouseSelectBackend::Influx(_) => super::super::DbType::InfluxDB,
    }
}

crate::impl_unified_select_executor_methods!(SelectExecutor);

impl<'a, T: Model> SelectExecutor<'a, T> {
    pub fn fields<F, G>(self, f: F) -> Self
    where
        F: FnOnce(T::Where) -> G,
        G: crate::query::builder::GroupByColumns,
    {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => SelectExecutor::Sqlite(exec.fields(f)),
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => SelectExecutor::PostgreSQL(exec.fields(f)),
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => SelectExecutor::MySQL(exec.fields(f)),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => SelectExecutor::MSSQL(exec.fields(f)),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => SelectExecutor::DuckDB(exec.fields(f)),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, select) => {
                SelectExecutor::ClickHouse(db, select.fields(f))
            }
        }
    }

    pub fn query(self, query: impl Into<String>) -> Self {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => SelectExecutor::Sqlite(exec.query(query)),
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => SelectExecutor::PostgreSQL(exec.query(query)),
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => SelectExecutor::MySQL(exec.query(query)),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => SelectExecutor::MSSQL(exec.query(query)),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => SelectExecutor::DuckDB(exec.query(query)),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, select) => {
                SelectExecutor::ClickHouse(db, select.query(query))
            }
        }
    }

    pub fn mode(self, mode: crate::query::filter::FullTextMode) -> Self {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => SelectExecutor::Sqlite(exec.mode(mode)),
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => SelectExecutor::PostgreSQL(exec.mode(mode)),
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => SelectExecutor::MySQL(exec.mode(mode)),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => SelectExecutor::MSSQL(exec.mode(mode)),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => SelectExecutor::DuckDB(exec.mode(mode)),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, select) => {
                SelectExecutor::ClickHouse(db, select.mode(mode))
            }
        }
    }

    pub fn language(self, language: impl Into<String>) -> Self {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => SelectExecutor::Sqlite(exec.language(language)),
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => SelectExecutor::PostgreSQL(exec.language(language)),
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => SelectExecutor::MySQL(exec.language(language)),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => SelectExecutor::MSSQL(exec.language(language)),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => SelectExecutor::DuckDB(exec.language(language)),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, select) => {
                SelectExecutor::ClickHouse(db, select.language(language))
            }
        }
    }

    pub fn rank(self, rank: crate::query::filter::FullTextRank) -> Self {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => SelectExecutor::Sqlite(exec.rank(rank)),
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => SelectExecutor::PostgreSQL(exec.rank(rank)),
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => SelectExecutor::MySQL(exec.rank(rank)),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => SelectExecutor::MSSQL(exec.rank(rank)),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => SelectExecutor::DuckDB(exec.rank(rank)),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, select) => {
                SelectExecutor::ClickHouse(db, select.rank(rank))
            }
        }
    }
}

impl<'a, T: Model> FilterQuery<T> for SelectExecutor<'a, T> {
    fn append_filter_expr(self, expr: WhereExpr) -> Self {
        SelectExecutor::append_filter_expr(self, expr)
    }
}

impl<'a, T: Model> NamedFilterQuery<T> for SelectExecutor<'a, T> {
    /// 命名过滤器以 `ContextFilter` 形式下发到内部 Select 构建器:
    /// name 与 scope 级 context filter 共用同一份 `(model_table, name)` 键,
    /// `without_filter(name)` 因此可同时撤销查询级与 scope 级同名过滤器。
    fn apply_named_filter(self, name: &'static str, expr: WhereExpr) -> Self {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => SelectExecutor::Sqlite(
                exec.with_context_filters(vec![ContextFilter::new::<T>(name, expr)]),
            ),
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => SelectExecutor::PostgreSQL(
                exec.with_context_filters(vec![ContextFilter::new::<T>(name, expr)]),
            ),
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => SelectExecutor::MySQL(
                exec.with_context_filters(vec![ContextFilter::new::<T>(name, expr)]),
            ),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => SelectExecutor::MSSQL(
                exec.with_context_filters(vec![ContextFilter::new::<T>(name, expr)]),
            ),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => SelectExecutor::DuckDB(
                exec.with_context_filters(vec![ContextFilter::new::<T>(name, expr)]),
            ),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, select) => SelectExecutor::ClickHouse(
                db,
                NamedFilterQuery::<T>::apply_named_filter(select, name, expr),
            ),
        }
    }
}

impl<'a, T: Model> WithoutFilterQuery<T> for SelectExecutor<'a, T> {
    fn without_filter(self, name: &'static str) -> Self {
        SelectExecutor::without_filter(self, name)
    }
}

// 本块的 join/derived 分派方法参数仅由 SQL 后端分支消费;
// clickhouse/influxdb-only 组合下落 Unsupported,参数不被使用属预期
#[cfg_attr(
    not(any(
        feature = "sqlite",
        feature = "postgresql",
        feature = "mysql",
        feature = "mssql",
        feature = "duckdb"
    )),
    allow(unused_variables)
)]
impl<'a, T: Model> SelectExecutor<'a, T> {
    fn select_model<R: Model>(&self) -> SelectExecutor<'a, R> {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => SelectExecutor::Sqlite(exec.select_model::<R>()),
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => {
                SelectExecutor::PostgreSQL(exec.select_model::<R>())
            }
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => SelectExecutor::MySQL(exec.select_model::<R>()),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => SelectExecutor::MSSQL(exec.select_model::<R>()),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => SelectExecutor::DuckDB(exec.select_model::<R>()),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, select) => SelectExecutor::ClickHouse(
                *db,
                Select::default().with_context_filters(select.context_filters()),
            ),
        }
    }

    pub fn to_sql(&self) -> crate::Result<SqlStatement> {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => exec.to_sql(),
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => exec.to_sql(),
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => exec.to_sql(),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => exec.to_sql(),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => exec.to_sql(),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, select) => {
                let backend = clickhouse_select_backend_db_type(*db);
                let (sql, params) = select.try_to_sql_with_params(backend)?;
                Ok(SqlStatement::single(backend, sql, params))
            }
        }
    }

    pub fn include<F, S>(self, f: F) -> IncludedSelectExecutor<'a, T, S>
    where
        F: FnOnce(T::Where) -> S,
        S: RelationSelection<T>,
    {
        let where_obj = T::Where::default();
        IncludedSelectExecutor {
            select: self,
            selection: f(where_obj),
            _marker: std::marker::PhantomData,
        }
    }

    pub(crate) async fn select_related_with_selection<S>(
        &self,
        keys: Vec<Value>,
        selection: &S,
    ) -> crate::Result<Vec<S::Target>>
    where
        S: RelationSelection<T> + RelationNestedLoader<'a, T> + Send + Sync,
        S::Target: Send + Sync,
        S::Via: Send + Sync,
        T: 'static + Send + Sync,
    {
        match selection.path_info()? {
            RelationPathInfo::Direct { relation } => {
                self.select_target_models::<S>(relation.target_key, keys, selection)
                    .await
            }
            RelationPathInfo::Through {
                via_relation,
                target_relation,
                ..
            } => {
                let via_items = self.select_via_models::<S>(via_relation, keys).await?;
                let target_keys = via_items
                    .iter()
                    .filter_map(|item| item.column_value(target_relation.local_key))
                    .collect();
                self.select_target_models::<S>(target_relation.target_key, target_keys, selection)
                    .await
            }
        }
    }

    async fn select_target_models<S>(
        &self,
        target_key: &str,
        keys: Vec<Value>,
        selection: &S,
    ) -> crate::Result<Vec<S::Target>>
    where
        S: RelationSelection<T> + RelationNestedLoader<'a, T> + Send + Sync,
        S::Target: Send + Sync,
        S::Via: Send + Sync,
        T: 'static + Send + Sync,
    {
        let values = relation_filter_values(keys);
        if values.is_empty() {
            return Ok(Vec::new());
        }

        let mut exec = self.select_model::<S::Target>().filter(|_| {
            WhereExpr::from_filter(FilterExpr::In {
                column: target_key.to_string(),
                values,
            })
        });

        for filter in selection.filters().iter().cloned() {
            exec = exec.filter(|_| WhereExpr::from_filter(filter));
        }

        for order in selection.order_by().iter().cloned() {
            exec = exec.order_by(|_| order);
        }

        if selection.range_start().is_some() || selection.range_end().is_some() {
            exec = exec.range(crate::query::builder::RangeBounds {
                start: selection.range_start(),
                end: selection.range_end(),
            });
        }

        let mut related = exec.collect::<Vec<S::Target>>().await?;
        let target_select = self.select_model::<S::Target>();
        selection.load_nested(&target_select, &mut related).await?;
        Ok(related)
    }

    async fn select_via_models<S>(
        &self,
        via_relation: &RelationInfo,
        keys: Vec<Value>,
    ) -> crate::Result<Vec<S::Via>>
    where
        S: RelationSelection<T>,
        S::Via: Send + Sync,
    {
        let values = relation_filter_values(keys);
        if values.is_empty() {
            return Ok(Vec::new());
        }

        self.select_model::<S::Via>()
            .filter(|_| {
                WhereExpr::from_filter(FilterExpr::In {
                    column: via_relation.target_key.to_string(),
                    values,
                })
            })
            .collect::<Vec<S::Via>>()
            .await
    }

    pub(crate) async fn preload_models_with_selection<S>(
        &self,
        owners: &mut [T],
        selection: S,
    ) -> crate::Result<()>
    where
        S: RelationSelection<T> + RelationNestedLoader<'a, T> + Send + Sync,
        S::Target: Send + Sync,
        S::Via: Send + Sync,
        T: 'static + Send + Sync,
    {
        let path = selection.path_info()?;
        let owner_relation = relation_owner_key(path);
        let owner_keys = owners
            .iter()
            .map(|owner| owner.relation_key_value(owner_relation))
            .collect::<crate::Result<Vec<_>>>()?;

        match path {
            RelationPathInfo::Direct { relation } => {
                let related = self
                    .select_target_models::<S>(relation.target_key, owner_keys, &selection)
                    .await?;
                let mut grouped: std::collections::HashMap<String, Vec<S::Target>> =
                    std::collections::HashMap::new();
                for item in related {
                    if let Some(key) = item.column_value(relation.target_key) {
                        grouped
                            .entry(common_helpers::model_value_key(&key))
                            .or_default()
                            .push(item);
                    }
                }

                for owner in owners {
                    let key = owner.relation_key_value(relation)?;
                    let values = grouped
                        .get(&common_helpers::model_value_key(&key))
                        .cloned()
                        .unwrap_or_default();
                    owner.assign_relation(relation.name, values)?;
                }
            }
            RelationPathInfo::Through {
                relation,
                via_relation,
                target_relation,
            } => {
                let via_items = self
                    .select_via_models::<S>(via_relation, owner_keys)
                    .await?;
                let mut target_keys_by_owner: std::collections::HashMap<String, Vec<String>> =
                    std::collections::HashMap::new();

                for item in &via_items {
                    if let (Some(owner_key), Some(target_key)) = (
                        item.column_value(via_relation.target_key),
                        item.column_value(target_relation.local_key),
                    ) {
                        let target_key = common_helpers::model_value_key(&target_key);
                        target_keys_by_owner
                            .entry(common_helpers::model_value_key(&owner_key))
                            .or_default()
                            .push(target_key.clone());
                    }
                }

                let target_key_values = via_items
                    .iter()
                    .filter_map(|item| item.column_value(target_relation.local_key))
                    .collect();
                let related = self
                    .select_target_models::<S>(
                        target_relation.target_key,
                        target_key_values,
                        &selection,
                    )
                    .await?;
                let mut targets_by_key: std::collections::HashMap<String, Vec<S::Target>> =
                    std::collections::HashMap::new();
                for item in &related {
                    if let Some(key) = item.column_value(target_relation.target_key) {
                        targets_by_key
                            .entry(common_helpers::model_value_key(&key))
                            .or_default()
                            .push(item.clone());
                    }
                }

                for owner in owners {
                    let key = owner.relation_key_value(via_relation)?;
                    let key = common_helpers::model_value_key(&key);
                    let values = target_keys_by_owner
                        .get(&key)
                        .map(|target_keys| {
                            target_keys
                                .iter()
                                .flat_map(|target_key| {
                                    targets_by_key.get(target_key).into_iter().flatten()
                                })
                                .cloned()
                                .collect()
                        })
                        .unwrap_or_default();
                    owner.assign_relation(relation.name, values)?;
                }
            }
        }

        Ok(())
    }

    /// 添加关联表查询
    ///
    /// 与构建器层 `Select::from::<R>()` 保持单泛型形态:关联表类型由 R 指定,
    /// 主表类型就是当前执行器的 T(`select::<User>().from::<Role>()`)。
    pub fn from<R: Model>(self) -> RelatedSelectExecutor<'a, T, R>
    where
        T: Model + 'static,
    {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => {
                RelatedSelectExecutor::Sqlite(exec.from::<R>(), std::marker::PhantomData)
            }
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => {
                RelatedSelectExecutor::PostgreSQL(exec.from::<R>())
            }
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => RelatedSelectExecutor::MySQL(exec.from::<R>()),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => RelatedSelectExecutor::MSSQL(exec.from::<R>()),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => RelatedSelectExecutor::DuckDB(exec.from::<R>()),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, _) => RelatedSelectExecutor::Unsupported {
                backend: clickhouse_select_backend_db_type(db),
                feature: "related (multi-table) select on ClickHouse",
                _marker: std::marker::PhantomData,
            },
        }
    }

    /// 添加关联表查询(支持3个表)
    /// select::<User>().from3::<User, Role, Permission>()
    pub fn from3<R1: Model, R2: Model>(self) -> MultiTableSelectExecutor<'a, T, R1, R2>
    {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => MultiTableSelectExecutor::Sqlite(
                exec.from3::<R1, R2>(),
                std::marker::PhantomData,
            ),
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => {
                MultiTableSelectExecutor::PostgreSQL(exec.from3::<R1, R2>())
            }
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => {
                MultiTableSelectExecutor::MySQL(exec.from3::<R1, R2>())
            }
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => {
                MultiTableSelectExecutor::MSSQL(exec.from3::<R1, R2>())
            }
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => MultiTableSelectExecutor::DuckDB(
                exec.from3::<R1, R2>(),
                std::marker::PhantomData,
            ),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, _) => MultiTableSelectExecutor::Unsupported {
                backend: clickhouse_select_backend_db_type(db),
                feature: "related (multi-table) select",
                _marker: std::marker::PhantomData,
            },
        }
    }

    /// 添加关联表查询(支持4个表)
    /// select::<User>().from4::<User, Role, Permission, Department>()
    pub fn from4<R1: Model, R2: Model, R3: Model>(
        self,
    ) -> FourTableSelectExecutor<'a, T, R1, R2, R3>
    {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => FourTableSelectExecutor::Sqlite(
                exec.from4::<R1, R2, R3>(),
                std::marker::PhantomData,
            ),
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => {
                FourTableSelectExecutor::PostgreSQL(exec.from4::<R1, R2, R3>())
            }
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => {
                FourTableSelectExecutor::MySQL(exec.from4::<R1, R2, R3>())
            }
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => {
                FourTableSelectExecutor::MSSQL(exec.from4::<R1, R2, R3>())
            }
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => FourTableSelectExecutor::DuckDB(
                exec.from4::<R1, R2, R3>(),
                std::marker::PhantomData,
            ),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, _) => FourTableSelectExecutor::Unsupported {
                backend: clickhouse_select_backend_db_type(db),
                feature: "related (multi-table) select",
                _marker: std::marker::PhantomData,
            },
        }
    }

    /// 添加 LEFT JOIN 查询
    pub fn left_join<J: Model>(
        self,
        f: impl FnOnce(T::Where, J::Where) -> WhereExpr,
    ) -> LeftJoinedSelectExecutor<'a, T, J> {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => {
                LeftJoinedSelectExecutor::Sqlite(exec.left_join::<J>(f), std::marker::PhantomData)
            }
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => {
                LeftJoinedSelectExecutor::PostgreSQL(exec.left_join::<J>(f))
            }
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => LeftJoinedSelectExecutor::MySQL(exec.left_join::<J>(f)),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => LeftJoinedSelectExecutor::MSSQL(exec.left_join::<J>(f)),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => {
                LeftJoinedSelectExecutor::DuckDB(exec.left_join::<J>(f))
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, _) => LeftJoinedSelectExecutor::Unsupported {
                backend: clickhouse_select_backend_db_type(db),
                feature: "LEFT JOIN select",
                _marker: std::marker::PhantomData,
            },
        }
    }

    /// 添加 INNER JOIN 查询
    pub fn inner_join<J: Model>(
        self,
        f: impl FnOnce(T::Where, J::Where) -> WhereExpr,
    ) -> InnerJoinedSelectExecutor<'a, T, J> {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => {
                InnerJoinedSelectExecutor::Sqlite(exec.inner_join::<J>(f), std::marker::PhantomData)
            }
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => {
                InnerJoinedSelectExecutor::PostgreSQL(exec.inner_join::<J>(f))
            }
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => {
                InnerJoinedSelectExecutor::MySQL(exec.inner_join::<J>(f))
            }
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => {
                InnerJoinedSelectExecutor::MSSQL(exec.inner_join::<J>(f))
            }
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => {
                InnerJoinedSelectExecutor::DuckDB(exec.inner_join::<J>(f))
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, _) => InnerJoinedSelectExecutor::Unsupported {
                backend: clickhouse_select_backend_db_type(db),
                feature: "INNER JOIN select",
                _marker: std::marker::PhantomData,
            },
        }
    }

    /// 添加 RIGHT JOIN 查询
    pub fn right_join<J: Model>(
        self,
        f: impl FnOnce(T::Where, J::Where) -> WhereExpr,
    ) -> RightJoinedSelectExecutor<'a, T, J> {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => {
                RightJoinedSelectExecutor::Sqlite(exec.right_join::<J>(f), std::marker::PhantomData)
            }
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => {
                RightJoinedSelectExecutor::PostgreSQL(exec.right_join::<J>(f))
            }
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => {
                RightJoinedSelectExecutor::MySQL(exec.right_join::<J>(f))
            }
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => {
                RightJoinedSelectExecutor::MSSQL(exec.right_join::<J>(f))
            }
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => {
                RightJoinedSelectExecutor::DuckDB(exec.right_join::<J>(f))
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, _) => RightJoinedSelectExecutor::Unsupported {
                backend: clickhouse_select_backend_db_type(db),
                feature: "RIGHT JOIN select",
                _marker: std::marker::PhantomData,
            },
        }
    }

    pub fn left_join_derived<J: Model>(
        self,
        derived: DerivedSelect<J>,
        f: impl FnOnce(T::Where, J::Where) -> WhereExpr,
    ) -> LeftJoinedSelectExecutor<'a, T, J> {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => LeftJoinedSelectExecutor::Sqlite(
                exec.left_join_derived::<J>(derived, f),
                std::marker::PhantomData,
            ),
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => {
                LeftJoinedSelectExecutor::PostgreSQL(exec.left_join_derived::<J>(derived, f))
            }
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => {
                LeftJoinedSelectExecutor::MySQL(exec.left_join_derived::<J>(derived, f))
            }
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => {
                LeftJoinedSelectExecutor::MSSQL(exec.left_join_derived::<J>(derived, f))
            }
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => {
                LeftJoinedSelectExecutor::DuckDB(exec.left_join_derived::<J>(derived, f))
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, _) => LeftJoinedSelectExecutor::Unsupported {
                backend: clickhouse_select_backend_db_type(db),
                feature: "JOIN select with a derived table",
                _marker: std::marker::PhantomData,
            },
        }
    }

    pub fn inner_join_derived<J: Model>(
        self,
        derived: DerivedSelect<J>,
        f: impl FnOnce(T::Where, J::Where) -> WhereExpr,
    ) -> InnerJoinedSelectExecutor<'a, T, J> {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => InnerJoinedSelectExecutor::Sqlite(
                exec.inner_join_derived::<J>(derived, f),
                std::marker::PhantomData,
            ),
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => {
                InnerJoinedSelectExecutor::PostgreSQL(exec.inner_join_derived::<J>(derived, f))
            }
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => {
                InnerJoinedSelectExecutor::MySQL(exec.inner_join_derived::<J>(derived, f))
            }
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => {
                InnerJoinedSelectExecutor::MSSQL(exec.inner_join_derived::<J>(derived, f))
            }
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => {
                InnerJoinedSelectExecutor::DuckDB(exec.inner_join_derived::<J>(derived, f))
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, _) => InnerJoinedSelectExecutor::Unsupported {
                backend: clickhouse_select_backend_db_type(db),
                feature: "JOIN select with a derived table",
                _marker: std::marker::PhantomData,
            },
        }
    }

    pub fn right_join_derived<J: Model>(
        self,
        derived: DerivedSelect<J>,
        f: impl FnOnce(T::Where, J::Where) -> WhereExpr,
    ) -> RightJoinedSelectExecutor<'a, T, J> {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => RightJoinedSelectExecutor::Sqlite(
                exec.right_join_derived::<J>(derived, f),
                std::marker::PhantomData,
            ),
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => {
                RightJoinedSelectExecutor::PostgreSQL(exec.right_join_derived::<J>(derived, f))
            }
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => {
                RightJoinedSelectExecutor::MySQL(exec.right_join_derived::<J>(derived, f))
            }
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => {
                RightJoinedSelectExecutor::MSSQL(exec.right_join_derived::<J>(derived, f))
            }
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => {
                RightJoinedSelectExecutor::DuckDB(exec.right_join_derived::<J>(derived, f))
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, _) => RightJoinedSelectExecutor::Unsupported {
                backend: clickhouse_select_backend_db_type(db),
                feature: "JOIN select with a derived table",
                _marker: std::marker::PhantomData,
            },
        }
    }

    pub fn collect<C: FromIterator<T> + 'static>(&self) -> CollectFuture<'a, T, C>
    where
        T: 'static,
    {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => CollectFuture::Sqlite(exec.clone().collect::<C>()),
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => {
                CollectFuture::PostgreSQL(exec.clone_with_client().collect::<C>())
            }
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => {
                CollectFuture::MySQL(exec.clone_with_pool().collect::<C>())
            }
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => {
                CollectFuture::MSSQL(exec.clone_with_pool().collect::<C>())
            }
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => CollectFuture::DuckDB(exec.clone().collect::<C>()),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, select) => {
                CollectFuture::ClickHouse(
                    *db,
                    select.clone(),
                    std::marker::PhantomData,
                )
            }
        }
    }

    /// 执行查询并返回第一条记录
    pub fn first(self) -> FirstFuture<'a, T>
    where
        T: 'static,
    {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => FirstFuture::Sqlite(exec.first()),
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => FirstFuture::PostgreSQL(exec.first()),
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => FirstFuture::MySQL(exec.first()),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => FirstFuture::MSSQL(exec.first()),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => FirstFuture::DuckDB(exec.first()),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, select) => FirstFuture::ClickHouse(db, select),
        }
    }

    /// COUNT 聚合函数。
    ///
    /// 返回行数(`usize`);关联/多表查询的同谓词行数统计
    /// (`RelatedSelectExecutor::count` 等)在统一层强转为同一 `usize`
    /// 类型,分页场景两个入口可直接混用。
    pub fn count<F, C>(self, f: F) -> AggregateFuture<'a, T, usize>
    where
        F: FnOnce(<T as Model>::Where) -> crate::query::builder::TypedColumn<C, T>,
    {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => {
                AggregateFuture::Sqlite(exec.count(f), std::marker::PhantomData)
            }
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => AggregateFuture::PostgreSQL(exec.count(f)),
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => AggregateFuture::MySQL(exec.count(f)),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => AggregateFuture::MSSQL(exec.count(f)),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => AggregateFuture::DuckDB(exec.count(f)),
            // ClickHouse/InfluxDB 都是聚合引擎:聚合 SELECT 走既有
            // select_values 单列执行路径(InfluxQL 的 AVG 映射为 MEAN)
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, select) => {
                AggregateFuture::ClickHouse(db, select.count(f), std::marker::PhantomData)
            }
        }
    }

    /// SUM 聚合函数
    pub fn sum<F, C>(self, f: F) -> AggregateFuture<'a, T, C::Output>
    where
        F: FnOnce(<T as Model>::Where) -> crate::query::builder::TypedColumn<C, T>,
        C: crate::query::builder::AggregateResultType + 'static,
    {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => {
                AggregateFuture::Sqlite(exec.sum(f), std::marker::PhantomData)
            }
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => AggregateFuture::PostgreSQL(exec.sum(f)),
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => AggregateFuture::MySQL(exec.sum(f)),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => AggregateFuture::MSSQL(exec.sum(f)),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => AggregateFuture::DuckDB(exec.sum(f)),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, select) => {
                AggregateFuture::ClickHouse(db, select.sum(f), std::marker::PhantomData)
            }
        }
    }

    /// AVG 聚合函数
    pub fn avg<F, C>(self, f: F) -> AggregateFuture<'a, T, Option<f64>>
    where
        F: FnOnce(<T as Model>::Where) -> crate::query::builder::TypedColumn<C, T>,
        C: crate::query::builder::AggregateResultType + 'static,
    {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => {
                AggregateFuture::Sqlite(exec.avg(f), std::marker::PhantomData)
            }
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => AggregateFuture::PostgreSQL(exec.avg(f)),
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => AggregateFuture::MySQL(exec.avg(f)),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => AggregateFuture::MSSQL(exec.avg(f)),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => AggregateFuture::DuckDB(exec.avg(f)),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, select) => {
                AggregateFuture::ClickHouse(db, select.avg(f), std::marker::PhantomData)
            }
        }
    }

    /// MAX 聚合函数
    pub fn max<F, C>(self, f: F) -> AggregateFuture<'a, T, C::Output>
    where
        F: FnOnce(<T as Model>::Where) -> crate::query::builder::TypedColumn<C, T>,
        C: crate::query::builder::AggregateResultType + 'static,
    {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => {
                AggregateFuture::Sqlite(exec.max(f), std::marker::PhantomData)
            }
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => AggregateFuture::PostgreSQL(exec.max(f)),
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => AggregateFuture::MySQL(exec.max(f)),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => AggregateFuture::MSSQL(exec.max(f)),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => AggregateFuture::DuckDB(exec.max(f)),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, select) => {
                AggregateFuture::ClickHouse(db, select.max(f), std::marker::PhantomData)
            }
        }
    }

    /// MIN 聚合函数
    pub fn min<F, C>(self, f: F) -> AggregateFuture<'a, T, C::Output>
    where
        F: FnOnce(<T as Model>::Where) -> crate::query::builder::TypedColumn<C, T>,
        C: crate::query::builder::AggregateResultType + 'static,
    {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => {
                AggregateFuture::Sqlite(exec.min(f), std::marker::PhantomData)
            }
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => AggregateFuture::PostgreSQL(exec.min(f)),
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => AggregateFuture::MySQL(exec.min(f)),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => AggregateFuture::MSSQL(exec.min(f)),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => AggregateFuture::DuckDB(exec.min(f)),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, select) => {
                AggregateFuture::ClickHouse(db, select.min(f), std::marker::PhantomData)
            }
        }
    }
}

/// 统一的 DeleteExecutor 枚举
pub enum DeleteExecutor<'a, T: Model> {
    #[cfg(feature = "sqlite")]
    Sqlite(
        sqlite_backend::DeleteExecutor<T>,
        std::marker::PhantomData<&'a ()>,
    ),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::DeleteExecutor<'a, T>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::DeleteExecutor<'a, T>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::DeleteExecutor<'a, T>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::DeleteExecutor<T>),
    /// 能力矩阵门控产物:`row_delete: false` 的后端在 [`Database::delete`] /
    /// `PooledConnection::delete` 构造时落入该变体。
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        _marker: std::marker::PhantomData<&'a T>,
    },
}

crate::impl_unified_delete_executor!(DeleteExecutor);

impl<'a, T: Model> DeleteExecutor<'a, T> {
    /// 设置拆表路由键值(渲染 `{表名}_{路由值}` 子表名)。
    // route 仅由 SQL 后端分支消费(极简 feature 组合下分派臂被裁剪属预期)
    #[allow(unused_variables)]
    pub fn route_table(
        self,
        key: impl Into<String>,
        value: impl crate::model::TableRouteValue,
    ) -> Self {
        let mut route = crate::model::TableRoute::new();
        route.insert(key, value);
        self.with_table_route(route)
    }

    /// 合并拆表路由(已有同名字段值不被覆盖)。
    // route 仅由 SQL 后端分支消费(极简 feature 组合下分派臂被裁剪属预期)
    #[allow(unused_variables)]
    pub fn with_table_route(self, route: crate::model::TableRoute) -> Self {
        match self {
            #[cfg(feature = "sqlite")]
            DeleteExecutor::Sqlite(exec, phantom) => {
                DeleteExecutor::Sqlite(exec.with_table_route(route), phantom)
            }
            #[cfg(feature = "postgresql")]
            DeleteExecutor::PostgreSQL(exec) => {
                DeleteExecutor::PostgreSQL(exec.with_table_route(route))
            }
            #[cfg(feature = "mysql")]
            DeleteExecutor::MySQL(exec) => DeleteExecutor::MySQL(exec.with_table_route(route)),
            #[cfg(feature = "mssql")]
            DeleteExecutor::MSSQL(exec) => DeleteExecutor::MSSQL(exec.with_table_route(route)),
            #[cfg(feature = "duckdb")]
            DeleteExecutor::DuckDB(exec) => DeleteExecutor::DuckDB(exec.with_table_route(route)),
            unsupported @ DeleteExecutor::Unsupported { .. } => unsupported,
        }
    }
}

impl<'a, T: Model> NamedFilterQuery<T> for DeleteExecutor<'a, T> {
    fn apply_named_filter(self, _name: &'static str, expr: WhereExpr) -> Self {
        self.filter(|_| expr)
    }
}

impl<'a, T: Model> super::SqlExecutor for DeleteExecutor<'a, T> {
    type Output = u64;

    fn to_sql(&self) -> crate::Result<SqlStatement> {
        DeleteExecutor::to_sql(self)
    }

    // sql 仅由 SQL 后端分支消费;influxdb-only 组合下恒走 Unsupported
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb"
        )),
        allow(unused_variables)
    )]
    async fn execute_with_sql(self, sql: SqlStatement) -> crate::Result<Self::Output> {
        match self {
            #[cfg(feature = "sqlite")]
            DeleteExecutor::Sqlite(exec, _) => exec.execute_with_sql(sql).await,
            #[cfg(feature = "postgresql")]
            DeleteExecutor::PostgreSQL(exec) => exec.execute_with_sql(sql).await,
            #[cfg(feature = "mysql")]
            DeleteExecutor::MySQL(exec) => exec.execute_with_sql(sql).await,
            #[cfg(feature = "mssql")]
            DeleteExecutor::MSSQL(exec) => exec.execute_with_sql(sql).await,
            #[cfg(feature = "duckdb")]
            DeleteExecutor::DuckDB(exec) => exec.execute_with_sql(sql).await,
            DeleteExecutor::Unsupported {
                backend, feature, ..
            } => Err(unsupported_feature(backend, feature)),
        }
    }
}

/// 按块删除结果。
///
/// `blocks_dropped` 尽力而为(回退路径为 0);`rows_deleted` 仅回退路径
/// (行删除实现)能报告。
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BlockDeleteResult {
    /// 删除的块数。
    pub blocks_dropped: u64,
    /// 影响行数(仅回退路径有值)。
    pub rows_deleted: Option<u64>,
}

impl BlockDeleteResult {
    /// 回退路径结果:仅报告行数。
    // 仅 PG/OLTP 后端的行删除路径消费;clickhouse/influxdb-only 组合下无调用方属预期
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb"
        )),
        allow(dead_code)
    )]
    pub(crate) fn from_row_count(rows: u64) -> Self {
        Self {
            blocks_dropped: 0,
            rows_deleted: Some(rows),
        }
    }
}

/// 统一的按块删除执行器。
///
/// - `PostgreSQL` 变体同时服务 PostgreSQL/TimescaleDB(`drop_chunks`,无扩展时
///   回退行删除)与 QuestDB(`DROP PARTITION`)。
/// - `ClickHouse` 变体枚举既有分区后合并为一条 `ALTER TABLE ... DROP PARTITION`。
/// - 其余 OLTP 后端走 `Fallback`:按对齐边界执行行删除。
pub enum BlockDeleteExecutor<'a, T: Model> {
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::BlockDeleteExecutor<'a, T>),
    #[cfg(feature = "clickhouse")]
    ClickHouse(clickhouse_backend::BlockDeleteExecutor<'a, T>),
    #[cfg(feature = "influxdb")]
    InfluxDB(influxdb_backend::BlockDeleteExecutor<'a, T>),
    /// OLTP 后端回退路径:`DELETE FROM t WHERE <对齐时间边界>`。
    #[cfg(any(
        feature = "sqlite",
        feature = "mysql",
        feature = "mssql",
        feature = "duckdb"
    ))]
    Fallback {
        db_type: super::super::DbType,
        key: Option<crate::abstract_layer::common::common_helpers::BlockKey>,
        range: Option<crate::abstract_layer::common::common_helpers::BlockRange>,
        delete: DeleteExecutor<'a, T>,
    },
}

crate::impl_unified_block_delete_executor!(BlockDeleteExecutor);

impl<'a, T: Model> BlockDeleteExecutor<'a, T> {
    /// 设置拆表路由键值(渲染 `{表名}_{路由值}` 子表名)。
    // route 仅由 PostgreSQL/Fallback 分支消费(极简 feature 组合下分派臂被裁剪属预期)
    #[allow(unused_variables)]
    pub fn route_table(
        self,
        key: impl Into<String>,
        value: impl crate::model::TableRouteValue,
    ) -> Self {
        let mut route = crate::model::TableRoute::new();
        route.insert(key, value);
        self.with_table_route(route)
    }

    /// 合并拆表路由(已有同名字段值不被覆盖)。
    // route 仅由 PostgreSQL/Fallback 分支消费(极简 feature 组合下分派臂被裁剪属预期)
    #[allow(unused_variables)]
    pub fn with_table_route(self, route: crate::model::TableRoute) -> Self {
        match self {
            #[cfg(feature = "postgresql")]
            BlockDeleteExecutor::PostgreSQL(exec) => {
                BlockDeleteExecutor::PostgreSQL(exec.with_table_route(route))
            }
            // route key 仅 PostgreSQL/表名模板语义,此后端忽略
            #[cfg(feature = "clickhouse")]
            this @ BlockDeleteExecutor::ClickHouse(..) => this,
            // route key 仅 PostgreSQL/表名模板语义,此后端忽略
            #[cfg(feature = "influxdb")]
            this @ BlockDeleteExecutor::InfluxDB(..) => this,
            #[cfg(any(
                feature = "sqlite",
                feature = "mysql",
                feature = "mssql",
                feature = "duckdb"
            ))]
            BlockDeleteExecutor::Fallback {
                db_type,
                key,
                range,
                delete,
            } => BlockDeleteExecutor::Fallback {
                db_type,
                key,
                range,
                delete: delete.with_table_route(route),
            },
        }
    }
}

#[cfg(any(
    feature = "sqlite",
    feature = "mysql",
    feature = "mssql",
    feature = "duckdb"
))]
impl<'a, T: Model> BlockDeleteExecutor<'a, T> {
    pub(crate) fn fallback(
        db_type: super::super::DbType,
        delete: DeleteExecutor<'a, T>,
    ) -> Self {
        BlockDeleteExecutor::Fallback {
            db_type,
            key: crate::abstract_layer::common::common_helpers::resolve_block_key::<T>(db_type)
                .ok(),
            range: None,
            delete,
        }
    }
}

impl<'a, T: Model> super::SqlExecutor for BlockDeleteExecutor<'a, T> {
    type Output = BlockDeleteResult;

    fn to_sql(&self) -> crate::Result<SqlStatement> {
        BlockDeleteExecutor::to_sql(self)
    }

    // sql 仅由 SQL 后端分支消费;influxdb-only 组合下恒走 Unsupported
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb",
            feature = "clickhouse"
        )),
        allow(unused_variables)
    )]
    async fn execute_with_sql(self, sql: SqlStatement) -> crate::Result<Self::Output> {
        match self {
            #[cfg(feature = "postgresql")]
            BlockDeleteExecutor::PostgreSQL(exec) => exec
                .execute_with_sql(sql)
                .await
                .map(BlockDeleteResult::from_row_count),
            #[cfg(feature = "clickhouse")]
            BlockDeleteExecutor::ClickHouse(exec) => exec.execute_with_sql(sql).await,
            #[cfg(feature = "influxdb")]
            BlockDeleteExecutor::InfluxDB(_) => Err(unsupported_feature(
                super::super::DbType::InfluxDB,
                "block delete execute_with_sql (the native backend uses the HTTP delete API)",
            )),
            #[cfg(any(
                feature = "sqlite",
                feature = "mysql",
                feature = "mssql",
                feature = "duckdb"
            ))]
            BlockDeleteExecutor::Fallback { delete, .. } => delete
                .execute_with_sql(sql)
                .await
                .map(BlockDeleteResult::from_row_count),
        }
    }

    async fn execute(self) -> crate::Result<Self::Output> {
        BlockDeleteExecutor::execute(self).await
    }
}

/// 统一的 UpdateExecutor 枚举
pub enum UpdateExecutor<'a, T: Model> {
    #[cfg(feature = "sqlite")]
    Sqlite(
        sqlite_backend::UpdateExecutor<T>,
        std::marker::PhantomData<&'a ()>,
    ),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::UpdateExecutor<'a, T>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::UpdateExecutor<'a, T>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::UpdateExecutor<'a, T>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::UpdateExecutor<T>),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        _marker: std::marker::PhantomData<&'a T>,
    },
}

crate::impl_unified_update_executor!(UpdateExecutor);

impl<'a, T: Model> UpdateExecutor<'a, T> {
    /// 设置拆表路由键值(渲染 `{表名}_{路由值}` 子表名)。
    // route 仅由 SQL 后端分支消费(极简 feature 组合下分派臂被裁剪属预期)
    #[allow(unused_variables)]
    pub fn route_table(
        self,
        key: impl Into<String>,
        value: impl crate::model::TableRouteValue,
    ) -> Self {
        let mut route = crate::model::TableRoute::new();
        route.insert(key, value);
        self.with_table_route(route)
    }

    /// 合并拆表路由(已有同名字段值不被覆盖)。
    // route 仅由 SQL 后端分支消费(极简 feature 组合下分派臂被裁剪属预期)
    #[allow(unused_variables)]
    pub fn with_table_route(self, route: crate::model::TableRoute) -> Self {
        match self {
            #[cfg(feature = "sqlite")]
            UpdateExecutor::Sqlite(exec, phantom) => {
                UpdateExecutor::Sqlite(exec.with_table_route(route), phantom)
            }
            #[cfg(feature = "postgresql")]
            UpdateExecutor::PostgreSQL(exec) => {
                UpdateExecutor::PostgreSQL(exec.with_table_route(route))
            }
            #[cfg(feature = "mysql")]
            UpdateExecutor::MySQL(exec) => UpdateExecutor::MySQL(exec.with_table_route(route)),
            #[cfg(feature = "mssql")]
            UpdateExecutor::MSSQL(exec) => UpdateExecutor::MSSQL(exec.with_table_route(route)),
            #[cfg(feature = "duckdb")]
            UpdateExecutor::DuckDB(exec) => UpdateExecutor::DuckDB(exec.with_table_route(route)),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            unsupported @ UpdateExecutor::Unsupported { .. } => unsupported,
        }
    }
}

impl<'a, T: Model> UpdateExecutor<'a, T> {
    // model/fields 仅由 SQL 后端分支消费;clickhouse/influxdb-only 组合下落 Unsupported
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb"
        )),
        allow(unused_variables)
    )]
    pub(crate) fn set_model_columns(self, model: &T, fields: &[String]) -> Self {
        match self {
            #[cfg(feature = "sqlite")]
            UpdateExecutor::Sqlite(exec, phantom) => {
                UpdateExecutor::Sqlite(exec.set_model_fields(model, fields), phantom)
            }
            #[cfg(feature = "postgresql")]
            UpdateExecutor::PostgreSQL(exec) => {
                UpdateExecutor::PostgreSQL(exec.set_model_fields(model, fields))
            }
            #[cfg(feature = "mysql")]
            UpdateExecutor::MySQL(exec) => {
                UpdateExecutor::MySQL(exec.set_model_fields(model, fields))
            }
            #[cfg(feature = "mssql")]
            UpdateExecutor::MSSQL(exec) => {
                UpdateExecutor::MSSQL(exec.set_model_fields(model, fields))
            }
            #[cfg(feature = "duckdb")]
            UpdateExecutor::DuckDB(exec) => {
                UpdateExecutor::DuckDB(exec.set_model_fields(model, fields))
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            unsupported @ UpdateExecutor::Unsupported { .. } => unsupported,
        }
    }
}

impl<'a, T: Model> NamedFilterQuery<T> for UpdateExecutor<'a, T> {
    fn apply_named_filter(self, _name: &'static str, expr: WhereExpr) -> Self {
        self.filter(|_| expr)
    }
}

impl<'a, T: Model> super::SqlExecutor for UpdateExecutor<'a, T> {
    type Output = u64;

    fn to_sql(&self) -> crate::Result<SqlStatement> {
        UpdateExecutor::to_sql(self)
    }

    // sql 仅由 SQL 后端分支消费;clickhouse/influxdb-only 组合下恒走 Unsupported
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb"
        )),
        allow(unused_variables)
    )]
    async fn execute_with_sql(self, sql: SqlStatement) -> crate::Result<Self::Output> {
        match self {
            #[cfg(feature = "sqlite")]
            UpdateExecutor::Sqlite(exec, _) => exec.execute_with_sql(sql).await,
            #[cfg(feature = "postgresql")]
            UpdateExecutor::PostgreSQL(exec) => exec.execute_with_sql(sql).await,
            #[cfg(feature = "mysql")]
            UpdateExecutor::MySQL(exec) => exec.execute_with_sql(sql).await,
            #[cfg(feature = "mssql")]
            UpdateExecutor::MSSQL(exec) => exec.execute_with_sql(sql).await,
            #[cfg(feature = "duckdb")]
            UpdateExecutor::DuckDB(exec) => exec.execute_with_sql(sql).await,
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            UpdateExecutor::Unsupported {
                backend, feature, ..
            } => Err(unsupported_feature(backend, feature)),
        }
    }
}

pub struct ScopedDeleteExecutor<'a, T: Model> {
    pub(crate) inner: DeleteExecutor<'a, T>,
    pub(crate) context_filters: Vec<ContextFilter>,
    pub(crate) disabled_filters: Vec<&'static str>,
}

pub struct ScopedUpdateExecutor<'a, T: Model> {
    pub(crate) inner: UpdateExecutor<'a, T>,
    pub(crate) context_filters: Vec<ContextFilter>,
    pub(crate) disabled_filters: Vec<&'static str>,
}

fn scoped_filter_exprs<T: Model>(
    context_filters: &[ContextFilter],
    disabled_filters: &[&'static str],
) -> Vec<FilterExpr> {
    context_filters
        .iter()
        .filter(|filter| !disabled_filters.iter().any(|name| *name == filter.name()))
        .filter_map(ContextFilter::filter_for::<T>)
        .collect()
}

fn append_scoped_filters<T: Model>(
    statement: &mut SqlStatement,
    context_filters: &[ContextFilter],
    disabled_filters: &[&'static str],
) -> crate::Result<()> {
    let filters = scoped_filter_exprs::<T>(context_filters, disabled_filters);
    if filters.is_empty() {
        return Ok(());
    }

    for single in &mut statement.statements {
        // scope 条件的参数占位符追加在既有参数之后,与占位符编号保持一致
        let mut scope_sql = String::new();
        let mut param_idx = single.params.len() + 1;
        for (index, filter) in filters.iter().enumerate() {
            if index > 0 {
                scope_sql.push_str(" AND ");
            }
            common_helpers::format_filter_with_params(
                filter,
                &mut scope_sql,
                &mut param_idx,
                &mut single.params,
                statement.db_type,
            )?;
        }

        match find_toplevel_where(&single.sql) {
            // 已有 WHERE:把既有条件整体加括号再 AND,防止
            // "WHERE pk = ? OR pk = ?" 这类 OR 分支绕过租户过滤
            Some(insert_at) => {
                single.sql.insert(insert_at, '(');
                single.sql.push_str(") AND ");
                single.sql.push_str(&scope_sql);
            }
            None => {
                single.sql.push_str(" WHERE ");
                single.sql.push_str(&scope_sql);
            }
        }
    }

    Ok(())
}

/// 定位语句中顶层 WHERE 子句的条件起始位置("WHERE" 后的偏移)。
///
/// 扫描时跳过单引号字符串字面量与括号内的子查询,避免把
/// `SET x = (SELECT ... WHERE ...)` 或含 "WHERE" 的字面量误认为顶层 WHERE。
fn find_toplevel_where(sql: &str) -> Option<usize> {
    let bytes = sql.as_bytes();
    let mut depth = 0i32;
    let mut in_string = false;
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if in_string {
            if b == b'\'' {
                if i + 1 < bytes.len() && bytes[i + 1] == b'\'' {
                    i += 2;
                    continue;
                }
                in_string = false;
            }
        } else {
            match b {
                b'\'' => in_string = true,
                b'(' => depth += 1,
                b')' => depth -= 1,
                b'W' if depth == 0 => {
                    let is_word_start = i == 0 || bytes[i - 1] == b' ' || bytes[i - 1] == b'\n';
                    if is_word_start && sql[i..].starts_with("WHERE") {
                        let mut j = i + "WHERE".len();
                        while j < bytes.len() && bytes[j] == b' ' {
                            j += 1;
                        }
                        return Some(j);
                    }
                }
                _ => {}
            }
        }
        i += 1;
    }
    None
}

impl<'a, T: Model> ScopedDeleteExecutor<'a, T> {
    /// 设置拆表路由键值(渲染 `{表名}_{路由值}` 子表名)。
    pub fn route_table(
        mut self,
        key: impl Into<String>,
        value: impl crate::model::TableRouteValue,
    ) -> Self {
        self.inner = self.inner.route_table(key, value);
        self
    }

    /// 合并拆表路由(已有同名字段值不被覆盖)。
    pub fn with_table_route(mut self, route: crate::model::TableRoute) -> Self {
        self.inner = self.inner.with_table_route(route);
        self
    }

    pub fn filter<F, W>(mut self, f: F) -> Self
    where
        F: FnOnce(T::Where) -> W,
        W: Into<WhereExpr>,
    {
        self.inner = self.inner.filter(f);
        self
    }

    pub fn model(mut self, model: &T) -> Self {
        self.inner = self.inner.model(model);
        self
    }

    pub fn to_sql(&self) -> crate::Result<SqlStatement> {
        let mut statement = self.inner.to_sql()?;
        append_scoped_filters::<T>(
            &mut statement,
            &self.context_filters,
            &self.disabled_filters,
        )?;
        Ok(statement)
    }

    pub async fn execute(self) -> crate::Result<u64> {
        <Self as super::SqlExecutor>::execute(self).await
    }

    pub fn without_hooks(self) -> crate::WithoutHooksExecutor<Self> {
        crate::WithoutHooksExecutor(self)
    }

    /// 同义词,等价于 [`Self::execute`]。
    #[deprecated(since = "0.2.11", note = "use `execute()` instead")]
    pub async fn exec(self) -> crate::Result<u64> {
        self.execute().await
    }
}

impl<'a, T: Model> NamedFilterQuery<T> for ScopedDeleteExecutor<'a, T> {
    fn apply_named_filter(self, _name: &'static str, expr: WhereExpr) -> Self {
        self.filter(|_| expr)
    }
}

impl<'a, T: Model> WithoutFilterQuery<T> for ScopedDeleteExecutor<'a, T> {
    fn without_filter(mut self, name: &'static str) -> Self {
        if !self.disabled_filters.contains(&name) {
            self.disabled_filters.push(name);
        }
        self
    }
}

impl<'a, T: Model> super::SqlExecutor for ScopedDeleteExecutor<'a, T> {
    type Output = u64;

    fn to_sql(&self) -> crate::Result<SqlStatement> {
        ScopedDeleteExecutor::to_sql(self)
    }

    async fn execute_with_sql(self, sql: SqlStatement) -> crate::Result<Self::Output> {
        self.inner.execute_with_sql(sql).await
    }
}

impl<'a, T: Model> ScopedUpdateExecutor<'a, T> {
    /// 设置拆表路由键值(渲染 `{表名}_{路由值}` 子表名)。
    pub fn route_table(
        mut self,
        key: impl Into<String>,
        value: impl crate::model::TableRouteValue,
    ) -> Self {
        self.inner = self.inner.route_table(key, value);
        self
    }

    /// 合并拆表路由(已有同名字段值不被覆盖)。
    pub fn with_table_route(mut self, route: crate::model::TableRoute) -> Self {
        self.inner = self.inner.with_table_route(route);
        self
    }

    pub fn filter<F, W>(mut self, f: F) -> Self
    where
        F: FnOnce(T::Where) -> W,
        W: Into<WhereExpr>,
    {
        self.inner = self.inner.filter(f);
        self
    }

    pub fn set<F>(mut self, f: F) -> Self
    where
        F: FnOnce(&mut T::Update),
    {
        self.inner = self.inner.set(f);
        self
    }

    pub fn set_model<I: crate::model::Insertable<Model = T>>(mut self, models: I) -> Self {
        self.inner = self.inner.set_model(models);
        self
    }

    pub fn set_model_fields<I, F, M>(mut self, models: I, fields_fn: F) -> Self
    where
        I: crate::model::Insertable<Model = T>,
        F: FnOnce(T::Where) -> M,
        M: crate::query::builder::MapToResult,
    {
        self.inner = self.inner.set_model_fields(models, fields_fn);
        self
    }

    pub fn to_sql(&self) -> crate::Result<SqlStatement> {
        let mut statement = self.inner.to_sql()?;
        append_scoped_filters::<T>(
            &mut statement,
            &self.context_filters,
            &self.disabled_filters,
        )?;
        Ok(statement)
    }

    pub async fn execute(self) -> crate::Result<u64> {
        <Self as super::SqlExecutor>::execute(self).await
    }

    pub fn without_hooks(self) -> crate::WithoutHooksExecutor<Self> {
        crate::WithoutHooksExecutor(self)
    }
}

impl<'a, T: Model> NamedFilterQuery<T> for ScopedUpdateExecutor<'a, T> {
    fn apply_named_filter(self, _name: &'static str, expr: WhereExpr) -> Self {
        self.filter(|_| expr)
    }
}

impl<'a, T: Model> WithoutFilterQuery<T> for ScopedUpdateExecutor<'a, T> {
    fn without_filter(mut self, name: &'static str) -> Self {
        if !self.disabled_filters.contains(&name) {
            self.disabled_filters.push(name);
        }
        self
    }
}

impl<'a, T: Model> super::SqlExecutor for ScopedUpdateExecutor<'a, T> {
    type Output = u64;

    fn to_sql(&self) -> crate::Result<SqlStatement> {
        ScopedUpdateExecutor::to_sql(self)
    }

    async fn execute_with_sql(self, sql: SqlStatement) -> crate::Result<Self::Output> {
        self.inner.execute_with_sql(sql).await
    }
}

/// 统一的 CollectFuture 枚举
pub enum CollectFuture<'a, T: Model, C: FromIterator<T>> {
    #[cfg(feature = "sqlite")]
    Sqlite(sqlite_backend::CollectFuture<'a, T, C>),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::CollectFuture<'a, T, C>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::CollectFuture<'a, T, C>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::CollectFuture<'a, T, C>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::CollectFuture<'a, T, C>),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    ClickHouse(
        ClickHouseSelectBackend<'a>,
        crate::query::builder::Select<T>,
        std::marker::PhantomData<C>,
    ),
}

/// 统一的 FirstFuture 枚举
pub enum FirstFuture<'a, T: Model> {
    #[cfg(feature = "sqlite")]
    Sqlite(sqlite_backend::FirstFuture<'a, T>),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::FirstFuture<'a, T>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::FirstFuture<'a, T>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::FirstFuture<'a, T>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::FirstFuture<'a, T>),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    ClickHouse(
        ClickHouseSelectBackend<'a>,
        crate::query::builder::Select<T>,
    ),
}

/// 统一的 AggregateFuture 枚举
pub enum AggregateFuture<'a, T: Model, R> {
    #[cfg(feature = "sqlite")]
    Sqlite(
        sqlite_backend::AggregateFuture<T, R>,
        std::marker::PhantomData<&'a ()>,
    ),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::AggregateFuture<'a, T, R>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::AggregateFuture<'a, T, R>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::AggregateFuture<'a, T, R>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::AggregateFuture<T, R>),
    /// ClickHouse/InfluxDB 的聚合 SELECT:渲染为单列聚合查询后走
    /// select_values/raw_select_values 执行路径。
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    ClickHouse(
        ClickHouseSelectBackend<'a>,
        crate::query::builder::AggregateSelect<T, R>,
        std::marker::PhantomData<&'a R>,
    ),
}

crate::impl_unified_aggregate_future!(AggregateFuture);

/// 统一层"主表 + N 个关联表"执行器家族(RelatedSelectExecutor /
/// MultiTableSelectExecutor / FourTableSelectExecutor)的公共生成宏:
/// 统一执行器枚举、同谓词 COUNT Future 枚举、Future 的 IntoFuture 委托与
/// `count()` 入口一次生成,三个调用点只差类型名与关联表参数个数。
///
/// DuckDB 变体存在历史形态差异:RelatedSelectExecutor 为单字段,
/// Multi/Four 为 `(executor, PhantomData)` 双字段——通过可选的
/// `duckdb_extra` 注入额外字段以保持各自公开形状不变;`count()` 的
/// 解构使用剩余模式 `(exec, ..)` 同时兼容两种形态(PhantomData 为零
/// 大小,丢弃后重建语义等价)。
///
/// "主表行收集"Future 与 `collect()` 入口由
/// [`impl_unified_multi_table_collect`] 单独生成:宏转录中 `$($r),+`
/// 无法嵌套进可选段 `$(...)?`(可选段只有 1 个绑定,`+` 段有 N 个,
/// 转录深度无法对齐),拆成独立宏后各自在顶层重绑关联表参数。
/// Related 的 collect 由 `impl_unified_related_select_executor!` 生成,
/// 不使用本宏族。
macro_rules! impl_unified_multi_table_select_family {
    (
        $exec:ident, $future:ident,
        $exec_doc:literal, $future_doc:literal, $count_doc:literal,
        ($($r:ident),+)
        $(, duckdb_extra { $($duck_extra:tt)* })?
    ) => {
        #[doc = $exec_doc]
        pub enum $exec<'a, T: Model, $($r: Model),+> {
            #[cfg(feature = "sqlite")]
            Sqlite(
                sqlite_backend::$exec<T, $($r),+>,
                std::marker::PhantomData<&'a ()>,
            ),
            #[cfg(feature = "postgresql")]
            PostgreSQL(postgresql_backend::$exec<'a, T, $($r),+>),
            #[cfg(feature = "mysql")]
            MySQL(mysql_backend::$exec<'a, T, $($r),+>),
            #[cfg(feature = "mssql")]
            MSSQL(mssql_backend::$exec<'a, T, $($r),+>),
            #[cfg(feature = "duckdb")]
            DuckDB(
                duckdb_backend::$exec<T, $($r),+>
                $(, $($duck_extra)*)?
            ),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            #[doc(hidden)]
            Unsupported {
                backend: super::super::DbType,
                feature: &'static str,
                _marker: std::marker::PhantomData<&'a (T, $($r),+)>,
            },
        }

        #[doc = $future_doc]
        pub enum $future<'a, T: Model, $($r: Model),+> {
            #[cfg(feature = "sqlite")]
            Sqlite(
                sqlite_backend::$exec<T, $($r),+>,
                std::marker::PhantomData<&'a ()>,
            ),
            #[cfg(feature = "postgresql")]
            PostgreSQL(postgresql_backend::$exec<'a, T, $($r),+>),
            #[cfg(feature = "mysql")]
            MySQL(mysql_backend::$exec<'a, T, $($r),+>),
            #[cfg(feature = "mssql")]
            MSSQL(mssql_backend::$exec<'a, T, $($r),+>),
            #[cfg(feature = "duckdb")]
            DuckDB(
                duckdb_backend::$exec<T, $($r),+>,
                std::marker::PhantomData<&'a ()>,
            ),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            #[doc(hidden)]
            Unsupported {
                backend: super::super::DbType,
                feature: &'static str,
                _marker: std::marker::PhantomData<&'a (T, $($r),+)>,
            },
        }

        crate::impl_unified_related_count_future!(
            $future,
            count,
            [
                'a,
                T: crate::Model + 'static + std::marker::Send + std::marker::Sync,
                $($r: crate::Model + 'static + std::marker::Send + std::marker::Sync),+
            ],
            ['a, T, $($r),+]
        );

        impl<'a, T: Model + 'static, $($r: Model + 'static),+> $exec<'a, T, $($r),+> {
            #[doc = $count_doc]
            pub fn count(self) -> $future<'a, T, $($r),+> {
                match self {
                    #[cfg(feature = "sqlite")]
                    $exec::Sqlite(exec, phantom) => $future::Sqlite(exec, phantom),
                    #[cfg(feature = "postgresql")]
                    $exec::PostgreSQL(exec) => $future::PostgreSQL(exec),
                    #[cfg(feature = "mysql")]
                    $exec::MySQL(exec) => $future::MySQL(exec),
                    #[cfg(feature = "mssql")]
                    $exec::MSSQL(exec) => $future::MSSQL(exec),
                    #[cfg(feature = "duckdb")]
                    $exec::DuckDB(exec, ..) => {
                        $future::DuckDB(exec, std::marker::PhantomData)
                    }
                    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
                    $exec::Unsupported {
                        backend,
                        feature,
                        ..
                    } => $future::Unsupported {
                        backend,
                        feature,
                        _marker: std::marker::PhantomData,
                    },
                }
            }
        }
    };
}

/// "主表行收集"生成宏(L18:from3/from4 此前只能 count、无法取回行数据;
/// SQL 只选择主表列,解码路径与 related collect 相同):生成 `collect()`
/// 方法、收集 Future 枚举及其 IntoFuture 委托。与
/// [`impl_unified_multi_table_select_family`] 分离定义的原因见其文档。
macro_rules! impl_unified_multi_table_collect {
    (
        $exec:ident, $collect_future:ident,
        $method_doc:literal, $future_doc:literal,
        ($($r:ident),+)
    ) => {
        impl<'a, T: Model + 'static, $($r: Model + 'static),+> $exec<'a, T, $($r),+> {
            #[doc = $method_doc]
            pub fn collect(self) -> $collect_future<'a, T, $($r),+> {
                match self {
                    #[cfg(feature = "sqlite")]
                    $exec::Sqlite(exec, phantom) => {
                        $collect_future::Sqlite(exec, phantom)
                    }
                    #[cfg(feature = "postgresql")]
                    $exec::PostgreSQL(exec) => $collect_future::PostgreSQL(exec),
                    #[cfg(feature = "mysql")]
                    $exec::MySQL(exec) => $collect_future::MySQL(exec),
                    #[cfg(feature = "mssql")]
                    $exec::MSSQL(exec) => $collect_future::MSSQL(exec),
                    #[cfg(feature = "duckdb")]
                    $exec::DuckDB(exec, ..) => {
                        $collect_future::DuckDB(exec, std::marker::PhantomData)
                    }
                    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
                    $exec::Unsupported {
                        backend,
                        feature,
                        ..
                    } => $collect_future::Unsupported {
                        backend,
                        feature,
                        _marker: std::marker::PhantomData,
                    },
                }
            }
        }

        #[doc = $future_doc]
        pub enum $collect_future<'a, T: Model, $($r: Model),+> {
            #[cfg(feature = "sqlite")]
            Sqlite(
                sqlite_backend::$exec<T, $($r),+>,
                std::marker::PhantomData<&'a ()>,
            ),
            #[cfg(feature = "postgresql")]
            PostgreSQL(postgresql_backend::$exec<'a, T, $($r),+>),
            #[cfg(feature = "mysql")]
            MySQL(mysql_backend::$exec<'a, T, $($r),+>),
            #[cfg(feature = "mssql")]
            MSSQL(mssql_backend::$exec<'a, T, $($r),+>),
            #[cfg(feature = "duckdb")]
            DuckDB(
                duckdb_backend::$exec<T, $($r),+>,
                std::marker::PhantomData<&'a ()>,
            ),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            #[doc(hidden)]
            Unsupported {
                backend: super::super::DbType,
                feature: &'static str,
                _marker: std::marker::PhantomData<&'a (T, $($r),+)>,
            },
        }

        impl<
            'a,
            T: crate::Model + 'static + std::marker::Send + std::marker::Sync,
            $($r: crate::Model + 'static + std::marker::Send + std::marker::Sync),+
        > std::future::IntoFuture for $collect_future<'a, T, $($r),+>
        where
            Self: 'a,
        {
            type Output = crate::Result<Vec<T>>;
            type IntoFuture = std::pin::Pin<
                Box<dyn std::future::Future<Output = Self::Output> + Send + 'a>,
            >;

            fn into_future(self) -> Self::IntoFuture {
                match self {
                    #[cfg(feature = "sqlite")]
                    $collect_future::Sqlite(exec, _) => {
                        Box::pin(async move { exec.collect_rows().await })
                    }
                    #[cfg(feature = "postgresql")]
                    $collect_future::PostgreSQL(exec) => {
                        Box::pin(async move { exec.collect_rows().await })
                    }
                    #[cfg(feature = "mysql")]
                    $collect_future::MySQL(exec) => {
                        Box::pin(async move { exec.collect_rows().await })
                    }
                    #[cfg(feature = "mssql")]
                    $collect_future::MSSQL(exec) => {
                        Box::pin(async move { exec.collect_rows().await })
                    }
                    #[cfg(feature = "duckdb")]
                    $collect_future::DuckDB(exec, _) => {
                        Box::pin(async move { exec.collect_rows().await })
                    }
                    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
                    $collect_future::Unsupported {
                        backend,
                        feature,
                        ..
                    } => Box::pin(async move {
                        Err(unsupported_feature(backend, feature))
                    }),
                }
            }
        }
    };
}

impl_unified_multi_table_select_family!(
    RelatedSelectExecutor,
    RelatedCountFuture,
    "统一的 RelatedSelectExecutor 枚举",
    "统一的关联查询同谓词行数统计 Future(page.md 缺失一:分页 total_count 场景)。\n\n结果为与原子查询同谓词的 `SELECT COUNT(*)`,不受 range()/order_by() 影响。",
    "统计同谓词总行数(列表分页 total_count 用):\n生成 `SELECT COUNT(*) FROM (<原子查询>)`,不受 range()/order_by() 影响。\n\n返回 `usize`(统一层把后端的 `i64` 行数强转),与\n[`SelectExecutor::count`] 的返回类型一致。",
    (R)
);

/// 统一层"主表 + N 个关联表"执行器的主表拆表路由转发生成宏:
/// `route_table` / `with_table_route` 仅作用于主表,逐后端转发到内部
/// 执行器(最终落到 builder 层 `RelatedSelect`/`MultiTableSelect`/
/// `FourTableSelect` 的 `table_route`)。DuckDB 变体形状差异与
/// [`impl_unified_multi_table_select_family`] 一致,经 `duckdb_extra` 注入:
/// 第一个组插值进解构 pattern 尾部(`..`),第二个组插值进重建表达式尾部
/// (pattern 位置不接受类型化 token,故需要两组分别提供)。
macro_rules! impl_unified_multi_table_route {
    (
        $exec:ident, ($($r:ident),+)
        $(, duckdb_extra { $($duck_pat:tt)* } { $($duck_expr:tt)* })?
    ) => {
        impl<'a, T: Model, $($r: Model),+> $exec<'a, T, $($r),+> {
            /// 设置主表拆表路由键值(渲染 `{表名}_{路由值}` 子表名;关联表不路由)。
            // route 仅由 SQL 后端分支消费(极简 feature 组合下分派臂被裁剪属预期)
            #[allow(unused_variables)]
            pub fn route_table(
                self,
                key: impl Into<String>,
                value: impl crate::model::TableRouteValue,
            ) -> Self {
                let mut route = crate::model::TableRoute::new();
                route.insert(key, value);
                self.with_table_route(route)
            }

            /// 合并主表拆表路由(已有同名字段值不被覆盖)。
            // route 仅由 SQL 后端分支消费(极简 feature 组合下分派臂被裁剪属预期)
            #[allow(unused_variables)]
            pub fn with_table_route(self, route: crate::model::TableRoute) -> Self {
                match self {
                    #[cfg(feature = "sqlite")]
                    $exec::Sqlite(exec, phantom) => {
                        $exec::Sqlite(exec.with_table_route(route), phantom)
                    }
                    #[cfg(feature = "postgresql")]
                    $exec::PostgreSQL(exec) => $exec::PostgreSQL(exec.with_table_route(route)),
                    #[cfg(feature = "mysql")]
                    $exec::MySQL(exec) => $exec::MySQL(exec.with_table_route(route)),
                    #[cfg(feature = "mssql")]
                    $exec::MSSQL(exec) => $exec::MSSQL(exec.with_table_route(route)),
                    #[cfg(feature = "duckdb")]
                    $exec::DuckDB(exec $(, $($duck_pat)*)?) => $exec::DuckDB(
                        exec.with_table_route(route)
                        $(, $($duck_expr)*)?
                    ),
                    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
                    unsupported @ $exec::Unsupported { .. } => unsupported,
                }
            }
        }
    };
}

impl_unified_multi_table_route!(RelatedSelectExecutor, (R));

impl_unified_multi_table_select_family!(
    MultiTableSelectExecutor,
    MultiTableCountFuture,
    "统一的 MultiTableSelectExecutor 枚举",
    "统一的三表关联查询同谓词行数统计 Future。",
    "统计同谓词总行数(列表分页 total_count 用)。\n\n返回 `usize`(统一层把后端的 `i64` 行数强转),与\n[`SelectExecutor::count`] 的返回类型一致。",
    (R1, R2),
    duckdb_extra { std::marker::PhantomData<&'a ()> }
);

impl_unified_multi_table_route!(
    MultiTableSelectExecutor,
    (R1, R2),
    duckdb_extra { .. } { std::marker::PhantomData }
);

impl_unified_multi_table_collect!(
    MultiTableSelectExecutor,
    MultiTableCollectFuture,
    "执行查询并收集主表行(L18):多表关联 SQL 只选择主表列,\n返回 `Vec<T>`;关联表仅用于过滤。",
    "统一的三表关联查询主表行收集 Future(L18:from3 此前只能 count)。\n\nSQL 只选择主表列,返回 `Vec<T>`。",
    (R1, R2)
);

impl_unified_multi_table_select_family!(
    FourTableSelectExecutor,
    FourTableCountFuture,
    "统一的 FourTableSelectExecutor 枚举",
    "统一的四表关联查询同谓词行数统计 Future。",
    "统计同谓词总行数(列表分页 total_count 用)。\n\n返回 `usize`(统一层把后端的 `i64` 行数强转),与\n[`SelectExecutor::count`] 的返回类型一致。",
    (R1, R2, R3),
    duckdb_extra { std::marker::PhantomData<&'a ()> }
);

impl_unified_multi_table_route!(
    FourTableSelectExecutor,
    (R1, R2, R3),
    duckdb_extra { .. } { std::marker::PhantomData }
);

impl_unified_multi_table_collect!(
    FourTableSelectExecutor,
    FourTableCollectFuture,
    "执行查询并收集主表行(L18):多表关联 SQL 只选择主表列,\n返回 `Vec<T>`;关联表仅用于过滤。",
    "统一的四表关联查询主表行收集 Future(L18:from4 此前只能 count)。\n\nSQL 只选择主表列,返回 `Vec<T>`。",
    (R1, R2, R3)
);

/// 统一的 InnerJoinedSelectExecutor 枚举
pub enum InnerJoinedSelectExecutor<'a, T: Model, J: Model> {
    #[cfg(feature = "sqlite")]
    Sqlite(
        sqlite_backend::InnerJoinedSelectExecutor<T, J>,
        std::marker::PhantomData<&'a ()>,
    ),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::InnerJoinedSelectExecutor<'a, T, J>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::InnerJoinedSelectExecutor<'a, T, J>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::InnerJoinedSelectExecutor<'a, T, J>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::InnerJoinedSelectExecutor<T, J>),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        _marker: std::marker::PhantomData<&'a (T, J)>,
    },
}

/// 统一的 RightJoinedSelectExecutor 枚举
pub enum RightJoinedSelectExecutor<'a, T: Model, J: Model> {
    #[cfg(feature = "sqlite")]
    Sqlite(
        sqlite_backend::RightJoinedSelectExecutor<T, J>,
        std::marker::PhantomData<&'a ()>,
    ),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::RightJoinedSelectExecutor<'a, T, J>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::RightJoinedSelectExecutor<'a, T, J>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::RightJoinedSelectExecutor<'a, T, J>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::RightJoinedSelectExecutor<T, J>),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        _marker: std::marker::PhantomData<&'a (T, J)>,
    },
}

/// 统一的 LeftJoinedSelectExecutor 枚举
pub enum LeftJoinedSelectExecutor<'a, T: Model, J: Model> {
    #[cfg(feature = "sqlite")]
    Sqlite(
        sqlite_backend::LeftJoinedSelectExecutor<T, J>,
        std::marker::PhantomData<&'a ()>,
    ),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::LeftJoinedSelectExecutor<'a, T, J>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::LeftJoinedSelectExecutor<'a, T, J>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::LeftJoinedSelectExecutor<'a, T, J>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::LeftJoinedSelectExecutor<T, J>),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        _marker: std::marker::PhantomData<&'a (T, J)>,
    },
}

/// 统一的 LeftJoinCollectFuture 枚举
pub enum LeftJoinCollectFuture<'a, T: Model, J: Model> {
    #[cfg(feature = "sqlite")]
    Sqlite(
        sqlite_backend::LeftJoinCollectFuture<T, J>,
        std::marker::PhantomData<&'a ()>,
    ),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::LeftJoinCollectFuture<'a, T, J>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::LeftJoinCollectFuture<'a, T, J>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::LeftJoinCollectFuture<'a, T, J>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::LeftJoinCollectFuture<T, J>),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        _marker: std::marker::PhantomData<&'a (T, J)>,
    },
}

/// 统一的 InnerJoinCollectFuture 枚举
pub enum InnerJoinCollectFuture<'a, T: Model, J: Model> {
    #[cfg(feature = "sqlite")]
    Sqlite(
        sqlite_backend::InnerJoinCollectFuture<T, J>,
        std::marker::PhantomData<&'a ()>,
    ),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::InnerJoinCollectFuture<'a, T, J>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::InnerJoinCollectFuture<'a, T, J>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::InnerJoinCollectFuture<'a, T, J>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::InnerJoinCollectFuture<T, J>),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        _marker: std::marker::PhantomData<&'a (T, J)>,
    },
}

/// 统一的 RightJoinCollectFuture 枚举
pub enum RightJoinCollectFuture<'a, T: Model, J: Model> {
    #[cfg(feature = "sqlite")]
    Sqlite(
        sqlite_backend::RightJoinCollectFuture<T, J>,
        std::marker::PhantomData<&'a ()>,
    ),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::RightJoinCollectFuture<'a, T, J>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::RightJoinCollectFuture<'a, T, J>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::RightJoinCollectFuture<'a, T, J>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::RightJoinCollectFuture<T, J>),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        _marker: std::marker::PhantomData<&'a (T, J)>,
    },
}

crate::impl_unified_collect_future!(CollectFuture);

impl<'a, T: Model + 'static + std::marker::Send + std::marker::Sync> std::future::IntoFuture
    for FirstFuture<'a, T>
{
    type Output = crate::Result<Option<T>>;
    type IntoFuture =
        std::pin::Pin<Box<dyn std::future::Future<Output = Self::Output> + Send + 'a>>;

    fn into_future(self) -> Self::IntoFuture {
        match self {
            #[cfg(feature = "sqlite")]
            FirstFuture::Sqlite(future) => Box::pin(future.into_future()),
            #[cfg(feature = "postgresql")]
            FirstFuture::PostgreSQL(future) => Box::pin(future.into_future()),
            #[cfg(feature = "mysql")]
            FirstFuture::MySQL(future) => Box::pin(future.into_future()),
            #[cfg(feature = "mssql")]
            FirstFuture::MSSQL(future) => Box::pin(future.into_future()),
            #[cfg(feature = "duckdb")]
            FirstFuture::DuckDB(future) => Box::pin(future.into_future()),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            FirstFuture::ClickHouse(db, select) => {
                Box::pin(async move { clickhouse_select_first_on_backend(db, select).await })
            }
        }
    }
}

crate::impl_unified_related_select_executor!(RelatedSelectExecutor);

/// 统一的 RelatedCollectFuture 枚举
pub enum RelatedCollectFuture<'a, T: Model, R: Model> {
    #[cfg(feature = "sqlite")]
    Sqlite(
        sqlite_backend::RelatedCollectFuture<T, R>,
        std::marker::PhantomData<&'a ()>,
    ),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::RelatedCollectFuture<'a, T, R>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::RelatedCollectFuture<'a, T, R>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::RelatedCollectFuture<'a, T, R>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::RelatedCollectFuture<T, R>),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        _marker: std::marker::PhantomData<&'a (T, R)>,
    },
}

crate::impl_unified_related_collect_future!(RelatedCollectFuture);

/// 统一的 Transaction 枚举
pub enum Transaction<'a> {
    #[cfg(feature = "sqlite")]
    Sqlite(sqlite_backend::Transaction),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::Transaction<'a>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::Transaction<'a>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::Transaction<'a>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::Transaction),
    // 哨兵变体:仅在无携带生命周期的后端变体(如仅启用 sqlite/duckdb/clickhouse/
    // influxdb)时锚定 `'a`,使枚举在所有 feature 组合下可编译。
    // 携带 [`std::convert::Infallible`](无任何值)保证该变体在安全 Rust 中
    // 无法被构造——外部代码与内部代码均构造不出;match 分支对它做
    // void 消除(`match *infallible {}`)而非 `unreachable!()` panic。
    #[doc(hidden)]
    _Phantom(std::convert::Infallible, std::marker::PhantomData<&'a ()>),
}

/// 旧事务保存执行器名过渡别名(已合并为 [`SaveExecutor`],保留 re-export
/// 以兼容现有导入路径;事务入口 [`Transaction::save`] 返回的就是
/// [`SaveExecutor`] 的事务变体,`'tx` 参数仅为兼容旧签名保留)。
#[deprecated(
    since = "0.2.12",
    note = "TransactionSaveExecutor 已合并为 SaveExecutor,请改用 SaveExecutor"
)]
pub type TransactionSaveExecutor<'a, 'tx, T> = SaveExecutor<'a, T>;

/// Save 执行器的共享核心:dirty 列更新 + 图关系同步,写路径在给定事务上执行。
/// [`SaveExecutor`] 的自开事务路径与外部事务路径共用本函数,图保存语义只维护一份。
async fn save_dirty_columns_and_relations<T>(
    txn: &mut Transaction<'_>,
    model: &mut Tracked<T>,
) -> crate::Result<u64>
where
    T: WritableModel + crate::model::Model + crate::model::GraphWritable,
{
    let fields = model.dirty_columns();
    let mut affected = 0u64;
    if !fields.is_empty() {
        affected += txn
            .update::<T>()
            .set_model_columns(model.as_model(), &fields)
            .execute()
            .await?;
    }
    affected += model.sync_graph_relations(txn).await?;
    Ok(affected)
}

/// 池连接 save 的写核心(L24):在池连接上自开事务执行
/// [`save_dirty_columns_and_relations`],结束时提交/回滚(回滚失败走统一日志),
/// 与 [`Database::save`] 的自开事务路径语义一致。
async fn save_on_pooled_conn<T>(
    conn: &connection_pool::PooledConnection<'_>,
    model: &mut Tracked<T>,
) -> crate::Result<u64>
where
    T: WritableModel + crate::model::Model + crate::model::GraphWritable,
{
    let mut tx = conn.begin().await?;
    match save_dirty_columns_and_relations(&mut tx, model).await {
        Ok(affected) => {
            tx.commit().await?;
            Ok(affected)
        }
        Err(err) => {
            log_rollback_failure(tx.rollback().await);
            Err(err)
        }
    }
}

impl<'a, T: WritableModel + crate::model::GraphWritable> SaveExecutor<'a, T> {
    /// 池连接路径构造(L24):`PooledConnection::save` 委托此处。
    ///
    /// SQL 预渲染与启动闭包擦除同事务路径(池连接的内层生命周期 `'pool`
    /// 与外层借用 `'a` 不同,同样需要擦除);写核心自开事务并提交/回滚,
    /// 语义与 [`Database::save`] 一致。
    pub(crate) fn from_pooled<'pool>(
        conn: &'a connection_pool::PooledConnection<'pool>,
        model: &'a mut Tracked<T>,
    ) -> Self
    where
        'pool: 'a,
    {
        // SQL 预览在构造时渲染(dirty 列在执行器存续期被独占借用,不可再变)
        let sql = {
            let fields = model.dirty_columns();
            if fields.is_empty() {
                Ok(SqlStatement::batch(conn.db_type(), Vec::new()))
            } else {
                conn.update::<T>()
                    .set_model_columns(model.as_model(), &fields)
                    .to_sql()
            }
        };
        SaveExecutor {
            conn: SaveConn::Pooled {
                sql,
                run: Box::new(move |model: &'a mut Tracked<T>| -> SaveTxnFuture<'a, T> {
                    Box::pin(async move {
                        let result = save_on_pooled_conn(conn, model).await;
                        (result, model)
                    })
                }),
            },
            model,
        }
    }
}

#[cfg(any(feature = "postgresql", feature = "mysql", feature = "mssql"))]
pub(crate) fn isolation_level_sql(isolation: IsolationLevel) -> &'static str {
    match isolation {
        IsolationLevel::ReadUncommitted => "READ UNCOMMITTED",
        IsolationLevel::ReadCommitted => "READ COMMITTED",
        IsolationLevel::RepeatableRead => "REPEATABLE READ",
        IsolationLevel::Serializable => "SERIALIZABLE",
    }
}

/// 在事务开始后应用事务选项。
///
/// 可达路径仅为 SQLite/PostgreSQL/MSSQL/DuckDB(`begin_opts` 把 MySQL 固定
/// 路由到 `begin_with_opts`(选项必须在 BEGIN 前下发),QuestDB/ClickHouse/
/// InfluxDB 在 `begin()` 即被 `transactions: false` 拦截),其余后端在此
/// 防御性拒绝,避免矩阵漂移时静默忽略选项或在 BEGIN 后错误地下发
/// `SET TRANSACTION`。
#[cfg_attr(
    not(any(
        feature = "sqlite",
        feature = "postgresql",
        feature = "mssql",
        feature = "duckdb"
    )),
    allow(unused_variables)
)]
pub(crate) async fn apply_transaction_options(
    txn: &mut Transaction<'_>,
    options: TransactionOptions,
) -> crate::Result<()> {
    match txn.db_type() {
        #[cfg(feature = "sqlite")]
        super::super::DbType::Sqlite => {
            if options.isolation.is_some() || options.read_only {
                return Err(unsupported_feature(
                    super::super::DbType::Sqlite,
                    "transaction options on SQLite",
                ));
            }
            Ok(())
        }
        #[cfg(feature = "postgresql")]
        super::super::DbType::PostgreSQL => {
            if let Some(isolation) = options.isolation {
                txn.execute_sql(format!(
                    "SET TRANSACTION ISOLATION LEVEL {}",
                    isolation_level_sql(isolation)
                ))
                .await?;
            }
            if options.read_only {
                txn.execute_sql("SET TRANSACTION READ ONLY").await?;
            }
            Ok(())
        }
        #[cfg(feature = "mssql")]
        super::super::DbType::MSSQL => {
            if let Some(isolation) = options.isolation {
                txn.execute_sql(format!(
                    "SET TRANSACTION ISOLATION LEVEL {}",
                    isolation_level_sql(isolation)
                ))
                .await?;
            }
            if options.read_only {
                return Err(unsupported_feature(
                    super::super::DbType::MSSQL,
                    "read-only transactions",
                ));
            }
            Ok(())
        }
        #[cfg(feature = "duckdb")]
        super::super::DbType::DuckDB => {
            if options.isolation.is_some() || options.read_only {
                return Err(unsupported_feature(
                    super::super::DbType::DuckDB,
                    "transaction options on DuckDB",
                ));
            }
            Ok(())
        }
        // MySQL/QuestDB/ClickHouse/InfluxDB 正常不可达(见函数文档)。
        #[allow(unreachable_patterns)]
        _ => Err(unsupported_feature(txn.db_type(), "transaction options")),
    }
}

/// 事务内的作用域查询入口:与 [`DatabaseScope`] 一致地自动附加
/// context filters(多租户/软删除等)。写路径同样受到保护,
/// 避免事务内的更新/删除绕过租户隔离。
pub struct TransactionScope<'a, 'tx> {
    txn: &'tx Transaction<'a>,
    context_filters: Vec<ContextFilter>,
}

impl<'a, 'tx> TransactionScope<'a, 'tx> {
    /// 附加 context filter(如租户条件),对后续经此作用域发起的查询生效。
    pub fn with_context_filter<T: Model>(mut self, name: &'static str, expr: WhereExpr) -> Self {
        self.context_filters
            .push(ContextFilter::new::<T>(name, expr));
        self
    }

    /// 撤销同名 context filter(scope 级或查询级命名过滤器)。
    pub fn without_filter(mut self, name: &'static str) -> Self {
        self.context_filters
            .retain(|filter| filter.name() != name);
        self
    }

    pub fn select<T: Model>(&self) -> SelectExecutor<'_, T> {
        self.txn
            .select::<T>()
            .with_context_filters(self.context_filters.clone())
    }

    pub fn delete<T: WritableModel>(&self) -> ScopedDeleteExecutor<'_, T> {
        ScopedDeleteExecutor {
            inner: self.txn.delete::<T>(),
            context_filters: self.context_filters.clone(),
            disabled_filters: Vec::new(),
        }
    }

    pub fn update<T: WritableModel>(&self) -> ScopedUpdateExecutor<'_, T> {
        ScopedUpdateExecutor {
            inner: self.txn.update::<T>(),
            context_filters: self.context_filters.clone(),
            disabled_filters: Vec::new(),
        }
    }

    pub async fn find_by_id<T: Model + 'static + Send + Sync>(
        &self,
        key: impl crate::model::PrimaryKey,
    ) -> crate::Result<Option<T>> {
        find_by_id_with_executor(self.select::<T>(), key).await
    }
}

impl<'a> Transaction<'a> {
    /// 事务内的作用域查询入口(对齐 [`Database::scope`])。
    pub fn scope<'tx>(&'tx self) -> TransactionScope<'a, 'tx> {
        TransactionScope {
            txn: self,
            context_filters: Vec::new(),
        }
    }

    pub fn db_type(&self) -> super::super::DbType {
        match self {
            #[cfg(feature = "sqlite")]
            Transaction::Sqlite(_) => super::super::DbType::Sqlite,
            #[cfg(feature = "postgresql")]
            Transaction::PostgreSQL(_) => super::super::DbType::PostgreSQL,
            #[cfg(feature = "mysql")]
            Transaction::MySQL(_) => super::super::DbType::MySQL,
            #[cfg(feature = "mssql")]
            Transaction::MSSQL(_) => super::super::DbType::MSSQL,
            #[cfg(feature = "duckdb")]
            Transaction::DuckDB(_) => super::super::DbType::DuckDB,
            Transaction::_Phantom(infallible, _) => match *infallible {},
        }
    }

    pub fn select_sql<T>(&mut self, sql: impl IntoRawSql) -> RawSelectExecutor<'_, T> {
        // 共享引用 + Transaction 协变性:`&mut Transaction<'a>` 在此降级为
        // `&Transaction<'_>`,与 Database / 池路径共用一份 RawSelectExecutor。
        RawSelectExecutor::from_conn(ConnRef::Txn(self), sql.into_raw_sql())
    }

    /// 执行原生非查询 SQL 并返回影响的行数。
    ///
    /// 注意:事务后端不含 ClickHouse/InfluxDB(`transactions: false`),
    /// 本方法返回值在各可达后端上均有精确行数语义。
    pub async fn execute_sql(&mut self, sql: impl IntoRawSql) -> crate::Result<u64> {
        // L21:Database / 事务 / 池连接三路径共用一份后端分派。
        // 写路径:后端事务 exec_raw 为 &mut 接收器,走 ConnRefMut(见
        // select_sql 的读路径注释;Transaction 协变性允许 &mut 收缩)。
        exec_raw_sql_on(ConnRefMut::Txn(self), sql.into_raw_sql()).await
    }

    /// 在事务内执行一段受 SAVEPOINT 保护的闭包,失败时回滚到 SAVEPOINT。
    ///
    /// 以 [`Capabilities::savepoints`] 为准:DuckDB 不支持 SAVEPOINT 语法,
    /// 在此直接返回 `UnsupportedFeature` 而不是透传驱动层 Parser 错误。
    pub async fn savepoint<R, F>(&mut self, f: F) -> crate::Result<R>
    where
        F: for<'tx> FnOnce(&'tx mut Transaction<'a>) -> TransactionFuture<'tx, R>,
    {
        Capabilities::ensure(self.db_type(), |caps| caps.savepoints, "savepoints")?;
        let name = format!(
            "__ormer_savepoint_{}",
            SAVEPOINT_COUNTER.fetch_add(1, Ordering::Relaxed)
        );
        #[cfg(feature = "mssql")]
        let is_mssql = matches!(self.db_type(), super::super::DbType::MSSQL);
        #[cfg(not(feature = "mssql"))]
        let is_mssql = false;

        if is_mssql {
            self.execute_sql(format!("SAVE TRANSACTION {name}")).await?;
        } else {
            self.execute_sql(format!("SAVEPOINT {name}")).await?;
        }

        match f(self).await {
            Ok(value) => {
                if !is_mssql {
                    self.execute_sql(format!("RELEASE SAVEPOINT {name}"))
                        .await?;
                }
                Ok(value)
            }
            Err(err) => {
                // 回滚到 SAVEPOINT / RELEASE 的失败不覆盖主错误,但不能
                // 静默吞掉(L23:统一走回滚失败日志)。
                if is_mssql {
                    log_rollback_failure(
                        self.execute_sql(format!("ROLLBACK TRANSACTION {name}")).await,
                    );
                } else {
                    log_rollback_failure(
                        self.execute_sql(format!("ROLLBACK TO SAVEPOINT {name}")).await,
                    );
                    log_rollback_failure(
                        self.execute_sql(format!("RELEASE SAVEPOINT {name}")).await,
                    );
                }
                Err(err)
            }
        }
    }

    /// 提交事务
    pub async fn commit(self) -> crate::Result<()> {
        match self {
            #[cfg(feature = "sqlite")]
            Transaction::Sqlite(txn) => txn.commit().await,
            #[cfg(feature = "postgresql")]
            Transaction::PostgreSQL(txn) => txn.commit().await,
            #[cfg(feature = "mysql")]
            Transaction::MySQL(txn) => txn.commit().await,
            #[cfg(feature = "mssql")]
            Transaction::MSSQL(txn) => txn.commit().await,
            #[cfg(feature = "duckdb")]
            Transaction::DuckDB(txn) => txn.commit().await,
            Transaction::_Phantom(infallible, _) => match infallible {},
        }
    }

    /// 回滚事务
    pub async fn rollback(self) -> crate::Result<()> {
        match self {
            #[cfg(feature = "sqlite")]
            Transaction::Sqlite(txn) => txn.rollback().await,
            #[cfg(feature = "postgresql")]
            Transaction::PostgreSQL(txn) => txn.rollback().await,
            #[cfg(feature = "mysql")]
            Transaction::MySQL(txn) => txn.rollback().await,
            #[cfg(feature = "mssql")]
            Transaction::MSSQL(txn) => txn.rollback().await,
            #[cfg(feature = "duckdb")]
            Transaction::DuckDB(txn) => txn.rollback().await,
            Transaction::_Phantom(infallible, _) => match infallible {},
        }
    }

    /// 关闭并回滚事务
    pub async fn close(self) -> crate::Result<()> {
        match self {
            #[cfg(feature = "sqlite")]
            Transaction::Sqlite(txn) => txn.close().await,
            #[cfg(feature = "postgresql")]
            Transaction::PostgreSQL(txn) => txn.close().await,
            #[cfg(feature = "mysql")]
            Transaction::MySQL(txn) => txn.close().await,
            #[cfg(feature = "mssql")]
            Transaction::MSSQL(txn) => txn.close().await,
            #[cfg(feature = "duckdb")]
            Transaction::DuckDB(txn) => txn.close().await,
            Transaction::_Phantom(infallible, _) => match infallible {},
        }
    }

    /// 根据主键查找单条记录(事务中)
    pub async fn find_by_id<T: Model + 'static + std::marker::Send + std::marker::Sync>(
        &self,
        key: impl crate::model::PrimaryKey,
    ) -> crate::Result<Option<T>> {
        find_by_id_with_executor(self.select::<T>(), key).await
    }

    /// 创建 Select 查询执行器
    pub fn select<T: Model>(&self) -> SelectExecutor<'_, T> {
        match self {
            #[cfg(feature = "sqlite")]
            Transaction::Sqlite(txn) => SelectExecutor::Sqlite(txn.select::<T>()),
            #[cfg(feature = "postgresql")]
            Transaction::PostgreSQL(txn) => SelectExecutor::PostgreSQL(txn.select::<T>()),
            #[cfg(feature = "mysql")]
            Transaction::MySQL(txn) => SelectExecutor::MySQL(txn.select::<T>()),
            #[cfg(feature = "mssql")]
            Transaction::MSSQL(txn) => SelectExecutor::MSSQL(txn.select::<T>()),
            #[cfg(feature = "duckdb")]
            Transaction::DuckDB(txn) => SelectExecutor::DuckDB(txn.select::<T>()),
            Transaction::_Phantom(infallible, _) => match *infallible {},
        }
    }

    pub fn batch<'b, B>(&'b self, batch: B) -> BatchFuture<'b, B>
    where
        B: BatchQueries<'b>,
    {
        BatchFuture::new(batch)
    }

    pub fn batch_many<'b, I, Q>(&'b self, queries: I) -> BatchManyFuture<'b, Q>
    where
        I: IntoIterator<Item = Q>,
        Q: BatchQuery<'b>,
    {
        BatchManyFuture::new(queries)
    }

    /// 创建分组聚合查询执行器
    pub fn select_column<T: Model, V>(&self) -> ProjectionSelectExecutor<'_, T, V> {
        match self {
            #[cfg(feature = "sqlite")]
            Transaction::Sqlite(txn) => {
                ProjectionSelectExecutor::Sqlite(txn.select_column::<T, V>())
            }
            #[cfg(feature = "postgresql")]
            Transaction::PostgreSQL(txn) => {
                ProjectionSelectExecutor::PostgreSQL(txn.select_column::<T, V>())
            }
            #[cfg(feature = "mysql")]
            Transaction::MySQL(txn) => ProjectionSelectExecutor::MySQL(txn.select_column::<T, V>()),
            #[cfg(feature = "mssql")]
            Transaction::MSSQL(txn) => ProjectionSelectExecutor::MSSQL(txn.select_column::<T, V>()),
            #[cfg(feature = "duckdb")]
            Transaction::DuckDB(txn) => {
                ProjectionSelectExecutor::DuckDB(txn.select_column::<T, V>())
            }
            Transaction::_Phantom(infallible, _) => match *infallible {},
        }
    }

    /// 创建 Delete 执行器
    pub fn delete<T: WritableModel>(&self) -> DeleteExecutor<'_, T> {
        match self {
            #[cfg(feature = "sqlite")]
            Transaction::Sqlite(txn) => {
                DeleteExecutor::Sqlite(txn.delete::<T>(), std::marker::PhantomData)
            }
            #[cfg(feature = "postgresql")]
            Transaction::PostgreSQL(txn) => DeleteExecutor::PostgreSQL(txn.delete::<T>()),
            #[cfg(feature = "mysql")]
            Transaction::MySQL(txn) => DeleteExecutor::MySQL(txn.delete::<T>()),
            #[cfg(feature = "mssql")]
            Transaction::MSSQL(txn) => DeleteExecutor::MSSQL(txn.delete::<T>()),
            #[cfg(feature = "duckdb")]
            Transaction::DuckDB(txn) => DeleteExecutor::DuckDB(txn.delete::<T>()),
            Transaction::_Phantom(infallible, _) => match *infallible {},
        }
    }

    /// 创建 Update 执行器
    pub fn update<T: WritableModel>(&self) -> UpdateExecutor<'_, T> {
        match self {
            #[cfg(feature = "sqlite")]
            Transaction::Sqlite(txn) => {
                UpdateExecutor::Sqlite(txn.update::<T>(), std::marker::PhantomData)
            }
            #[cfg(feature = "postgresql")]
            Transaction::PostgreSQL(txn) => UpdateExecutor::PostgreSQL(txn.update::<T>()),
            #[cfg(feature = "mysql")]
            Transaction::MySQL(txn) => UpdateExecutor::MySQL(txn.update::<T>()),
            #[cfg(feature = "mssql")]
            Transaction::MSSQL(txn) => UpdateExecutor::MSSQL(txn.update::<T>()),
            #[cfg(feature = "duckdb")]
            Transaction::DuckDB(txn) => UpdateExecutor::DuckDB(txn.update::<T>()),
            Transaction::_Phantom(infallible, _) => match *infallible {},
        }
    }

    /// 保存 tracked 模型的 dirty 变更(在当前事务上执行,写完不提交不回滚)。
    ///
    /// 返回合并后的 [`SaveExecutor`] 事务路径(旧名 [`TransactionSaveExecutor`]
    /// 保留为过渡别名)。
    pub fn save<'op, T: WritableModel + crate::model::GraphWritable>(
        &'op mut self,
        model: &'op mut Tracked<T>,
    ) -> SaveExecutor<'op, T> {
        // SQL 预览在构造时渲染(dirty 列在执行器存续期被独占借用,不可再变)
        let sql = {
            let fields = model.dirty_columns();
            if fields.is_empty() {
                Ok(SqlStatement::batch(self.db_type(), Vec::new()))
            } else {
                self.update::<T>()
                    .set_model_columns(model.as_model(), &fields)
                    .to_sql()
            }
        };
        // 写核心启动闭包:`&'op mut Transaction<'a>` 在此装箱擦除 `'a`,
        // SaveExecutor 的公开形状保持单生命周期
        let txn = self;
        SaveExecutor {
            conn: SaveConn::Txn {
                sql,
                run: Box::new(move |model: &'op mut Tracked<T>| -> SaveTxnFuture<'op, T> {
                    Box::pin(async move {
                        let result = save_dirty_columns_and_relations(txn, model).await;
                        (result, model)
                    })
                }),
            },
            model,
        }
    }

    /// 插入记录 - 返回执行器(合并后返回 [`InsertExecutor`] 的事务变体,
    /// 旧名 [`TransactionInsertExecutor`] 保留为过渡别名)。
    // models 仅由本地后端分支消费;influxdb-only 组合下无消费方属预期
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb"
        )),
        allow(unused_variables)
    )]
    pub fn insert<I: crate::model::Insertable>(&mut self, models: I) -> InsertExecutor<'_, I> {
        match self {
            #[cfg(feature = "sqlite")]
            Transaction::Sqlite(txn) => InsertExecutor::SqliteTxn(txn.insert::<I>(models)),
            #[cfg(feature = "postgresql")]
            Transaction::PostgreSQL(txn) => {
                InsertExecutor::PostgreSQLTxn(txn.insert::<I>(models))
            }
            #[cfg(feature = "mysql")]
            Transaction::MySQL(txn) => InsertExecutor::MySQLTxn(txn.insert::<I>(models)),
            #[cfg(feature = "mssql")]
            Transaction::MSSQL(txn) => InsertExecutor::MSSQLTxn(txn.insert::<I>(models)),
            #[cfg(feature = "duckdb")]
            Transaction::DuckDB(txn) => InsertExecutor::DuckDBTxn(txn.insert::<I>(models)),
            Transaction::_Phantom(infallible, _) => match *infallible {},
        }
    }

    /// 插入或更新记录 - 返回执行器(合并后返回 [`InsertOrUpdateExecutor`]
    /// 的事务变体,旧名 [`TransactionInsertOrUpdateExecutor`] 保留为过渡别名)。
    // models 仅由本地后端分支消费;influxdb-only 组合下无消费方属预期
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb"
        )),
        allow(unused_variables)
    )]
    pub fn insert_or_update<I: crate::model::Insertable>(
        &mut self,
        models: I,
    ) -> InsertOrUpdateExecutor<'_, I> {
        match self {
            #[cfg(feature = "sqlite")]
            Transaction::Sqlite(txn) => {
                InsertOrUpdateExecutor::SqliteTxn(txn.insert_or_update::<I>(models))
            }
            #[cfg(feature = "postgresql")]
            Transaction::PostgreSQL(txn) => {
                InsertOrUpdateExecutor::PostgreSQLTxn(txn.insert_or_update::<I>(models))
            }
            #[cfg(feature = "mysql")]
            Transaction::MySQL(txn) => {
                InsertOrUpdateExecutor::MySQLTxn(txn.insert_or_update::<I>(models))
            }
            #[cfg(feature = "mssql")]
            Transaction::MSSQL(txn) => {
                InsertOrUpdateExecutor::MSSQLTxn(txn.insert_or_update::<I>(models))
            }
            #[cfg(feature = "duckdb")]
            Transaction::DuckDB(txn) => {
                InsertOrUpdateExecutor::DuckDBTxn(txn.insert_or_update::<I>(models))
            }
            Transaction::_Phantom(infallible, _) => match *infallible {},
        }
    }

    pub fn upsert<I: crate::model::Insertable>(
        &mut self,
        models: I,
    ) -> InsertOrUpdateExecutor<'_, I> {
        self.insert_or_update(models)
    }

    /// 插入或忽略记录 - 返回执行器(合并后返回 [`InsertOrIgnoreExecutor`]
    /// 的事务变体,旧名 [`TransactionInsertOrIgnoreExecutor`] 保留为过渡别名)。
    // models 仅由本地后端分支消费;influxdb-only 组合下无消费方属预期
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb"
        )),
        allow(unused_variables)
    )]
    pub fn insert_or_ignore<I: crate::model::Insertable>(
        &mut self,
        models: I,
    ) -> InsertOrIgnoreExecutor<'_, I> {
        match self {
            #[cfg(feature = "sqlite")]
            Transaction::Sqlite(txn) => {
                InsertOrIgnoreExecutor::SqliteTxn(txn.insert_or_ignore::<I>(models))
            }
            #[cfg(feature = "postgresql")]
            Transaction::PostgreSQL(txn) => {
                InsertOrIgnoreExecutor::PostgreSQLTxn(txn.insert_or_ignore::<I>(models))
            }
            #[cfg(feature = "mysql")]
            Transaction::MySQL(txn) => {
                InsertOrIgnoreExecutor::MySQLTxn(txn.insert_or_ignore::<I>(models))
            }
            #[cfg(feature = "mssql")]
            Transaction::MSSQL(txn) => {
                InsertOrIgnoreExecutor::MSSQLTxn(txn.insert_or_ignore::<I>(models))
            }
            #[cfg(feature = "duckdb")]
            Transaction::DuckDB(txn) => {
                InsertOrIgnoreExecutor::DuckDBTxn(txn.insert_or_ignore::<I>(models))
            }
            Transaction::_Phantom(infallible, _) => match *infallible {},
        }
    }
}

impl<'a> super::DbExecutor for Transaction<'a> {
    fn select<T: Model>(&self) -> SelectExecutor<'_, T> {
        Transaction::select::<T>(self)
    }

    fn select_column<T: Model, V>(&self) -> ProjectionSelectExecutor<'_, T, V> {
        Transaction::select_column::<T, V>(self)
    }
}

crate::impl_unified_join_executor!(LeftJoinedSelectExecutor);

impl<'a, T: Model, J: Model> LeftJoinedSelectExecutor<'a, T, J> {
    pub fn collect<C: FromIterator<(T, Option<J>)> + 'static>(
        &self,
    ) -> LeftJoinCollectFuture<'a, T, J>
    where
        T: 'static,
        J: 'static,
    {
        match self {
            #[cfg(feature = "sqlite")]
            LeftJoinedSelectExecutor::Sqlite(exec, phantom) => {
                LeftJoinCollectFuture::Sqlite(exec.clone().collect::<C>(), *phantom)
            }
            #[cfg(feature = "postgresql")]
            LeftJoinedSelectExecutor::PostgreSQL(exec) => {
                LeftJoinCollectFuture::PostgreSQL(exec.clone_with_client().collect::<C>())
            }
            #[cfg(feature = "mysql")]
            LeftJoinedSelectExecutor::MySQL(exec) => {
                LeftJoinCollectFuture::MySQL(exec.clone_with_pool().collect::<C>())
            }
            #[cfg(feature = "mssql")]
            LeftJoinedSelectExecutor::MSSQL(exec) => {
                LeftJoinCollectFuture::MSSQL(exec.clone_with_pool().collect::<C>())
            }
            #[cfg(feature = "duckdb")]
            LeftJoinedSelectExecutor::DuckDB(exec) => {
                LeftJoinCollectFuture::DuckDB(exec.collect::<C>())
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            LeftJoinedSelectExecutor::Unsupported {
                backend, feature, ..
            } => LeftJoinCollectFuture::Unsupported {
                backend: *backend,
                feature,
                _marker: std::marker::PhantomData,
            },
        }
    }
}

crate::impl_unified_join_executor!(InnerJoinedSelectExecutor);

impl<'a, T: Model, J: Model> InnerJoinedSelectExecutor<'a, T, J> {
    pub fn collect<C: FromIterator<(T, J)> + 'static>(&self) -> InnerJoinCollectFuture<'a, T, J>
    where
        T: 'static,
        J: 'static,
    {
        match self {
            #[cfg(feature = "sqlite")]
            InnerJoinedSelectExecutor::Sqlite(exec, phantom) => {
                InnerJoinCollectFuture::Sqlite(exec.clone().collect::<C>(), *phantom)
            }
            #[cfg(feature = "postgresql")]
            InnerJoinedSelectExecutor::PostgreSQL(exec) => {
                InnerJoinCollectFuture::PostgreSQL(exec.clone_with_client().collect::<C>())
            }
            #[cfg(feature = "mysql")]
            InnerJoinedSelectExecutor::MySQL(exec) => {
                InnerJoinCollectFuture::MySQL(exec.clone_with_pool().collect::<C>())
            }
            #[cfg(feature = "mssql")]
            InnerJoinedSelectExecutor::MSSQL(exec) => {
                InnerJoinCollectFuture::MSSQL(exec.clone_with_pool().collect::<C>())
            }
            #[cfg(feature = "duckdb")]
            InnerJoinedSelectExecutor::DuckDB(exec) => {
                InnerJoinCollectFuture::DuckDB(exec.collect::<C>())
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            InnerJoinedSelectExecutor::Unsupported {
                backend, feature, ..
            } => InnerJoinCollectFuture::Unsupported {
                backend: *backend,
                feature,
                _marker: std::marker::PhantomData,
            },
        }
    }
}

crate::impl_unified_join_executor!(RightJoinedSelectExecutor);

impl<'a, T: Model, J: Model> RightJoinedSelectExecutor<'a, T, J> {
    pub fn collect<C: FromIterator<(Option<T>, J)> + 'static>(
        &self,
    ) -> RightJoinCollectFuture<'a, T, J>
    where
        T: 'static,
        J: 'static,
    {
        match self {
            #[cfg(feature = "sqlite")]
            RightJoinedSelectExecutor::Sqlite(exec, phantom) => {
                RightJoinCollectFuture::Sqlite(exec.clone().collect::<C>(), *phantom)
            }
            #[cfg(feature = "postgresql")]
            RightJoinedSelectExecutor::PostgreSQL(exec) => {
                RightJoinCollectFuture::PostgreSQL(exec.clone_with_client().collect::<C>())
            }
            #[cfg(feature = "mysql")]
            RightJoinedSelectExecutor::MySQL(exec) => {
                RightJoinCollectFuture::MySQL(exec.clone_with_pool().collect::<C>())
            }
            #[cfg(feature = "mssql")]
            RightJoinedSelectExecutor::MSSQL(exec) => {
                RightJoinCollectFuture::MSSQL(exec.clone_with_pool().collect::<C>())
            }
            #[cfg(feature = "duckdb")]
            RightJoinedSelectExecutor::DuckDB(exec) => {
                RightJoinCollectFuture::DuckDB(exec.collect::<C>())
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            RightJoinedSelectExecutor::Unsupported {
                backend, feature, ..
            } => RightJoinCollectFuture::Unsupported {
                backend: *backend,
                feature,
                _marker: std::marker::PhantomData,
            },
        }
    }
}

crate::impl_unified_join_collect_future!(LeftJoinCollectFuture, crate::Result<Vec<(T, Option<J>)>>);

crate::impl_unified_join_collect_future!(InnerJoinCollectFuture, crate::Result<Vec<(T, J)>>);

crate::impl_unified_join_collect_future!(
    RightJoinCollectFuture,
    crate::Result<Vec<(Option<T>, J)>>
);

/// 统一的 Projection 查询执行器枚举(字段投影与分组聚合合一)
///
/// 由原 `MappedSelectExecutor`(字段投影)与 `GroupedSelectExecutor`(分组聚合)
/// 合并而来:`ProjectionSelect::grouping` 决定实际走的 SQL 路径。
pub enum ProjectionSelectExecutor<'a, T: Model, V> {
    #[cfg(feature = "sqlite")]
    Sqlite(sqlite_backend::ProjectionSelectExecutor<'a, T, V>),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::ProjectionSelectExecutor<'a, T, V>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::ProjectionSelectExecutor<'a, T, V>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::ProjectionSelectExecutor<'a, T, V>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::ProjectionSelectExecutor<'a, T, V>),
    /// ClickHouse 分组聚合:渲染 GROUP BY 聚合 SQL 后走
    /// `select_named_values`(JSONEachRowWithNames)按投影顺序解码。
    #[cfg(feature = "clickhouse")]
    ClickHouse(&'a clickhouse_backend::Database, ProjectionSelect<T, V>),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        _marker: std::marker::PhantomData<&'a (T, V)>,
    },
}

#[deprecated(
    since = "0.2.12",
    note = "MappedSelectExecutor 已合并为 ProjectionSelectExecutor,请改用 ProjectionSelectExecutor"
)]
pub type MappedSelectExecutor<'a, T, V> = ProjectionSelectExecutor<'a, T, V>;

#[deprecated(
    since = "0.2.12",
    note = "GroupedSelectExecutor 已合并为 ProjectionSelectExecutor,请改用 ProjectionSelectExecutor"
)]
pub type GroupedSelectExecutor<'a, T, V> = ProjectionSelectExecutor<'a, T, V>;

// 本块的 group_by/having 等分派方法参数仅由 SQL 后端分支消费;
// clickhouse/influxdb-only 组合下落 Unsupported,参数不被使用属预期
#[cfg_attr(
    not(any(
        feature = "sqlite",
        feature = "postgresql",
        feature = "mysql",
        feature = "mssql",
        feature = "duckdb"
    )),
    allow(unused_variables)
)]
impl<'a, T: Model, V> ProjectionSelectExecutor<'a, T, V> {
    /// 添加 GROUP BY 字段
    pub fn group_by<F, G>(self, f: F) -> Self
    where
        F: FnOnce(<T as Model>::Where) -> G,
        G: crate::query::builder::GroupByColumns,
    {
        match self {
            #[cfg(feature = "sqlite")]
            ProjectionSelectExecutor::Sqlite(exec) => {
                ProjectionSelectExecutor::Sqlite(exec.group_by(f))
            }
            #[cfg(feature = "postgresql")]
            ProjectionSelectExecutor::PostgreSQL(exec) => {
                ProjectionSelectExecutor::PostgreSQL(exec.group_by(f))
            }
            #[cfg(feature = "mysql")]
            ProjectionSelectExecutor::MySQL(exec) => ProjectionSelectExecutor::MySQL(exec.group_by(f)),
            #[cfg(feature = "mssql")]
            ProjectionSelectExecutor::MSSQL(exec) => ProjectionSelectExecutor::MSSQL(exec.group_by(f)),
            #[cfg(feature = "duckdb")]
            ProjectionSelectExecutor::DuckDB(exec) => {
                ProjectionSelectExecutor::DuckDB(exec.group_by(f))
            }
            #[cfg(feature = "clickhouse")]
            ProjectionSelectExecutor::ClickHouse(db, select) => {
                ProjectionSelectExecutor::ClickHouse(db, select.group_by(f))
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            unsupported @ ProjectionSelectExecutor::Unsupported { .. } => unsupported,
        }
    }

    /// 添加 HAVING 条件
    pub fn having<F, W>(self, f: F) -> Self
    where
        F: FnOnce(<T as Model>::Where) -> W,
        W: Into<crate::query::builder::WhereExpr>,
    {
        match self {
            #[cfg(feature = "sqlite")]
            ProjectionSelectExecutor::Sqlite(exec) => {
                ProjectionSelectExecutor::Sqlite(exec.having(f))
            }
            #[cfg(feature = "postgresql")]
            ProjectionSelectExecutor::PostgreSQL(exec) => {
                ProjectionSelectExecutor::PostgreSQL(exec.having(f))
            }
            #[cfg(feature = "mysql")]
            ProjectionSelectExecutor::MySQL(exec) => ProjectionSelectExecutor::MySQL(exec.having(f)),
            #[cfg(feature = "mssql")]
            ProjectionSelectExecutor::MSSQL(exec) => ProjectionSelectExecutor::MSSQL(exec.having(f)),
            #[cfg(feature = "duckdb")]
            ProjectionSelectExecutor::DuckDB(exec) => {
                ProjectionSelectExecutor::DuckDB(exec.having(f))
            }
            #[cfg(feature = "clickhouse")]
            ProjectionSelectExecutor::ClickHouse(db, select) => {
                ProjectionSelectExecutor::ClickHouse(db, select.having(f))
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            unsupported @ ProjectionSelectExecutor::Unsupported { .. } => unsupported,
        }
    }

    /// 添加 WHERE 条件(分组前过滤)
    pub fn filter<F, W>(self, f: F) -> Self
    where
        F: FnOnce(T::Where) -> W,
        W: Into<crate::query::builder::WhereExpr>,
    {
        match self {
            #[cfg(feature = "sqlite")]
            ProjectionSelectExecutor::Sqlite(exec) => {
                ProjectionSelectExecutor::Sqlite(exec.filter(f))
            }
            #[cfg(feature = "postgresql")]
            ProjectionSelectExecutor::PostgreSQL(exec) => {
                ProjectionSelectExecutor::PostgreSQL(exec.filter(f))
            }
            #[cfg(feature = "mysql")]
            ProjectionSelectExecutor::MySQL(exec) => ProjectionSelectExecutor::MySQL(exec.filter(f)),
            #[cfg(feature = "mssql")]
            ProjectionSelectExecutor::MSSQL(exec) => ProjectionSelectExecutor::MSSQL(exec.filter(f)),
            #[cfg(feature = "duckdb")]
            ProjectionSelectExecutor::DuckDB(exec) => {
                ProjectionSelectExecutor::DuckDB(exec.filter(f))
            }
            #[cfg(feature = "clickhouse")]
            ProjectionSelectExecutor::ClickHouse(db, select) => {
                ProjectionSelectExecutor::ClickHouse(db, select.filter(f))
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            unsupported @ ProjectionSelectExecutor::Unsupported { .. } => unsupported,
        }
    }

    /// 执行查询并收集结果
    pub fn collect<C>(&self) -> ProjectionCollectFuture<'a, T, V, C>
    where
        T: 'static,
        V: crate::model::FromRowValues + 'static,
        C: FromIterator<V> + 'static,
    {
        match self {
            #[cfg(feature = "sqlite")]
            ProjectionSelectExecutor::Sqlite(exec) => {
                ProjectionCollectFuture::Sqlite(exec.collect::<C>())
            }
            #[cfg(feature = "postgresql")]
            ProjectionSelectExecutor::PostgreSQL(exec) => {
                ProjectionCollectFuture::PostgreSQL(exec.collect::<C>())
            }
            #[cfg(feature = "mysql")]
            ProjectionSelectExecutor::MySQL(exec) => {
                ProjectionCollectFuture::MySQL(exec.collect::<C>())
            }
            #[cfg(feature = "mssql")]
            ProjectionSelectExecutor::MSSQL(exec) => {
                ProjectionCollectFuture::MSSQL(exec.collect::<C>())
            }
            #[cfg(feature = "duckdb")]
            ProjectionSelectExecutor::DuckDB(exec) => {
                ProjectionCollectFuture::DuckDB(exec.collect::<C>())
            }
            #[cfg(feature = "clickhouse")]
            ProjectionSelectExecutor::ClickHouse(db, select) => ProjectionCollectFuture::ClickHouse(
                db,
                select.clone(),
                std::marker::PhantomData,
            ),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            ProjectionSelectExecutor::Unsupported {
                backend, feature, ..
            } => ProjectionCollectFuture::Unsupported {
                backend: *backend,
                feature,
                _marker: std::marker::PhantomData,
            },
        }
    }

    pub fn as_model<R: Model>(self) -> crate::Result<DerivedSelect<R>>
    where
        T: Send + Sync + 'static,
        V: Send + Sync + 'static,
    {
        match self {
            #[cfg(feature = "sqlite")]
            ProjectionSelectExecutor::Sqlite(exec) => Ok(exec.as_model::<R>()),
            #[cfg(feature = "postgresql")]
            ProjectionSelectExecutor::PostgreSQL(exec) => Ok(exec.as_model::<R>()),
            #[cfg(feature = "mysql")]
            ProjectionSelectExecutor::MySQL(exec) => Ok(exec.as_model::<R>()),
            #[cfg(feature = "mssql")]
            ProjectionSelectExecutor::MSSQL(exec) => Ok(exec.as_model::<R>()),
            #[cfg(feature = "duckdb")]
            ProjectionSelectExecutor::DuckDB(exec) => Ok(exec.as_model::<R>()),
            #[cfg(feature = "clickhouse")]
            ProjectionSelectExecutor::ClickHouse(_, _) => Err(unsupported_feature(
                super::super::DbType::ClickHouse,
                "Model select_column on ClickHouse; use select_sql",
            )),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            ProjectionSelectExecutor::Unsupported {
                backend, feature, ..
            } => Err(unsupported_feature(backend, feature)),
        }
    }
}

impl<'a, T: Model, V> Clone for ProjectionSelectExecutor<'a, T, V> {
    fn clone(&self) -> Self {
        match self {
            #[cfg(feature = "sqlite")]
            ProjectionSelectExecutor::Sqlite(exec) => ProjectionSelectExecutor::Sqlite(exec.clone()),
            #[cfg(feature = "postgresql")]
            ProjectionSelectExecutor::PostgreSQL(exec) => {
                ProjectionSelectExecutor::PostgreSQL(exec.clone_with_client())
            }
            #[cfg(feature = "mysql")]
            ProjectionSelectExecutor::MySQL(exec) => {
                ProjectionSelectExecutor::MySQL(exec.clone_with_pool())
            }
            #[cfg(feature = "mssql")]
            ProjectionSelectExecutor::MSSQL(exec) => {
                ProjectionSelectExecutor::MSSQL(exec.clone_with_pool())
            }
            #[cfg(feature = "duckdb")]
            ProjectionSelectExecutor::DuckDB(exec) => ProjectionSelectExecutor::DuckDB(exec.clone()),
            #[cfg(feature = "clickhouse")]
            ProjectionSelectExecutor::ClickHouse(db, select) => {
                ProjectionSelectExecutor::ClickHouse(db, select.clone())
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            ProjectionSelectExecutor::Unsupported {
                backend, feature, ..
            } => ProjectionSelectExecutor::Unsupported {
                backend: *backend,
                feature,
                _marker: std::marker::PhantomData,
            },
        }
    }
}

/// 统一的 Projection Collect Future 枚举(字段投影与分组聚合合一)
pub enum ProjectionCollectFuture<'a, T: Model, V, C: FromIterator<V>> {
    #[cfg(feature = "sqlite")]
    Sqlite(sqlite_backend::ProjectionCollectFuture<'a, T, V, C>),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::ProjectionCollectFuture<'a, T, V, C>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::ProjectionCollectFuture<'a, T, V, C>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::ProjectionCollectFuture<'a, T, V, C>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::ProjectionCollectFuture<'a, T, V, C>),
    #[cfg(feature = "clickhouse")]
    ClickHouse(
        &'a clickhouse_backend::Database,
        ProjectionSelect<T, V>,
        std::marker::PhantomData<C>,
    ),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        _marker: std::marker::PhantomData<&'a (T, V, C)>,
    },
}

#[deprecated(
    since = "0.2.12",
    note = "MappedCollectFuture 已合并为 ProjectionCollectFuture,请改用 ProjectionCollectFuture"
)]
pub type MappedCollectFuture<'a, T, V, C> = ProjectionCollectFuture<'a, T, V, C>;

#[deprecated(
    since = "0.2.12",
    note = "GroupedCollectFuture 已合并为 ProjectionCollectFuture,请改用 ProjectionCollectFuture"
)]
pub type GroupedCollectFuture<'a, T, V, C> = ProjectionCollectFuture<'a, T, V, C>;

impl<
    'a,
    T: Model + 'static + std::marker::Send + std::marker::Sync,
    V: crate::model::FromRowValues + 'static + std::marker::Send + std::marker::Sync,
    C: FromIterator<V> + 'static,
> std::future::IntoFuture for ProjectionCollectFuture<'a, T, V, C>
{
    type Output = crate::Result<C>;
    type IntoFuture =
        std::pin::Pin<Box<dyn std::future::Future<Output = Self::Output> + Send + 'a>>;

    fn into_future(self) -> Self::IntoFuture {
        match self {
            #[cfg(feature = "sqlite")]
            ProjectionCollectFuture::Sqlite(future) => Box::pin(future.into_future()),
            #[cfg(feature = "postgresql")]
            ProjectionCollectFuture::PostgreSQL(future) => Box::pin(future.into_future()),
            #[cfg(feature = "mysql")]
            ProjectionCollectFuture::MySQL(future) => Box::pin(future.into_future()),
            #[cfg(feature = "mssql")]
            ProjectionCollectFuture::MSSQL(future) => Box::pin(future.into_future()),
            #[cfg(feature = "duckdb")]
            ProjectionCollectFuture::DuckDB(future) => Box::pin(future.into_future()),
            // 分组投影的输出列名由服务端返回(JSONEachRowWithNames 首行),
            // 按投影顺序解码为 V
            #[cfg(feature = "clickhouse")]
            ProjectionCollectFuture::ClickHouse(db, select, _) => Box::pin(async move {
                let (sql, params) = select.try_to_sql_with_params(super::super::DbType::ClickHouse)?;
                let (_, rows) = db
                    .select_named_values(RawSql::new(sql).with_params(params))
                    .await?;
                rows.iter()
                    .map(|values| V::from_row_values(values))
                    .collect()
            }),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            ProjectionCollectFuture::Unsupported {
                backend, feature, ..
            } => Box::pin(async move { Err(unsupported_feature(backend, feature)) }),
        }
    }
}

/// 统一的 ModelCollectWithFuture 枚举
pub enum ModelCollectWithFuture<'a, T: Model + 'static, V: 'static, C, M, F> {
    #[cfg(feature = "sqlite")]
    Sqlite(sqlite_backend::ModelCollectWithFuture<'a, T, V, C, M, F>),
    #[cfg(feature = "postgresql")]
    PostgreSQLCollect(
        postgresql_backend::ProjectionCollectFuture<'a, T, V, Vec<V>>,
        F,
        std::marker::PhantomData<&'a (T, C, M)>,
    ),
    #[cfg(feature = "mysql")]
    MySQLCollect(
        mysql_backend::ProjectionCollectFuture<'a, T, V, Vec<V>>,
        F,
        std::marker::PhantomData<&'a (T, C, M)>,
    ),
    #[cfg(feature = "mssql")]
    MSSQLCollect(
        mssql_backend::ProjectionCollectFuture<'a, T, V, Vec<V>>,
        F,
        std::marker::PhantomData<&'a (T, C, M)>,
    ),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::ModelCollectWithFuture<'a, T, V, C, M, F>),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    #[doc(hidden)]
    Unsupported {
        backend: super::super::DbType,
        feature: &'static str,
        _marker: std::marker::PhantomData<&'a (T, V, C, M, F)>,
    },
}

impl<'a, T: Model> SelectExecutor<'a, T> {
    /// 字段投影 - 将查询结果映射到单个字段或元组
    /// 支持:
    /// - 单字段:map_to(|r| r.uid) -> ProjectionSelectExecutor<'a, T, i32>
    /// - 元组:map_to(|r| (r.uid, r.id)) -> ProjectionSelectExecutor<'a, T, (i32, i32)>
    // f 仅由本地后端分支消费;clickhouse/influxdb-only 组合下落 Unsupported
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb"
        )),
        allow(unused_variables)
    )]
    pub fn map_to<F, M>(self, f: F) -> ProjectionSelectExecutor<'a, T, M::Output>
    where
        F: FnOnce(<T as Model>::Where) -> M,
        M: crate::query::builder::MapToResult,
    {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => ProjectionSelectExecutor::Sqlite(exec.map_to(f)),
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => {
                ProjectionSelectExecutor::PostgreSQL(exec.map_to(f))
            }
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => ProjectionSelectExecutor::MySQL(exec.map_to(f)),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => ProjectionSelectExecutor::MSSQL(exec.map_to(f)),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => ProjectionSelectExecutor::DuckDB(exec.map_to(f)),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, _) => ProjectionSelectExecutor::Unsupported {
                backend: clickhouse_select_backend_db_type(db),
                feature: "select capability on ClickHouse",
                _marker: std::marker::PhantomData,
            },
        }
    }

    /// 选择列(支持聚合函数)- 转换为分组查询
    pub fn select_column<F, V>(self, f: F) -> ProjectionSelectExecutor<'a, T, V>
    where
        F: FnOnce(<T as Model>::Where) -> V,
        V: crate::query::builder::SelectColumnResult,
    {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => {
                ProjectionSelectExecutor::Sqlite(exec.select_column(f))
            }
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => {
                ProjectionSelectExecutor::PostgreSQL(exec.select_column(f))
            }
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => ProjectionSelectExecutor::MySQL(exec.select_column(f)),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => ProjectionSelectExecutor::MSSQL(exec.select_column(f)),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => {
                ProjectionSelectExecutor::DuckDB(exec.select_column(f))
            }
            // 能力矩阵门控与 Database / 池连接入口共用同一判定与文案
            // (L19:clickhouse_projection_gate)。
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, select) => {
                let backend = clickhouse_select_backend_db_type(db);
                if let Some(feature) = clickhouse_projection_gate(backend) {
                    return ProjectionSelectExecutor::Unsupported {
                        backend,
                        feature,
                        _marker: std::marker::PhantomData,
                    };
                }
                #[cfg(feature = "clickhouse")]
                #[cfg_attr(not(feature = "influxdb"), allow(irrefutable_let_patterns))]
                if let ClickHouseSelectBackend::ClickHouse(db) = db {
                    return ProjectionSelectExecutor::ClickHouse(db, select.select_column(f));
                }
                #[cfg(not(feature = "clickhouse"))]
                {
                    // influxdb-only 构建时能力门控已在上方返回,仅为
                    // 穷尽性保留
                    let _ = (select, f);
                }
                ProjectionSelectExecutor::Unsupported {
                    backend,
                    feature: "GROUP BY aggregation",
                    _marker: std::marker::PhantomData,
                }
            }
        }
    }

    /// 字段投影到 ViewModel - 按目标视图声明的列集合投影源表列,
    /// 典型用于跳过 blob 等大字段的元数据查询。
    pub fn map_to_view<V: crate::model::ViewModel>(
        self,
    ) -> ProjectionSelectExecutor<'a, T, V> {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => {
                ProjectionSelectExecutor::Sqlite(exec.map_to_view::<V>())
            }
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => {
                ProjectionSelectExecutor::PostgreSQL(exec.map_to_view::<V>())
            }
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => {
                ProjectionSelectExecutor::MySQL(exec.map_to_view::<V>())
            }
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => {
                ProjectionSelectExecutor::MSSQL(exec.map_to_view::<V>())
            }
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => {
                ProjectionSelectExecutor::DuckDB(exec.map_to_view::<V>())
            }
            // 能力矩阵门控与 select_column 共用同一判定与文案。
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, _) => ProjectionSelectExecutor::Unsupported {
                backend: clickhouse_select_backend_db_type(db),
                feature: "view-model projection",
                _marker: std::marker::PhantomData,
            },
        }
    }
}

pub struct IncludedSelectExecutor<'a, T: Model, S: RelationSelection<T>> {
    select: SelectExecutor<'a, T>,
    selection: S,
    _marker: std::marker::PhantomData<S>,
}

impl<'a, T: Model, S: RelationSelection<T>> IncludedSelectExecutor<'a, T, S> {
    pub fn include<F, S2>(self, f: F) -> DoubleIncludedSelectExecutor<'a, T, S, S2>
    where
        F: FnOnce(T::Where) -> S2,
        S2: RelationSelection<T>,
    {
        DoubleIncludedSelectExecutor {
            select: self.select,
            first: self.selection,
            second: f(T::Where::default()),
            _marker: std::marker::PhantomData,
        }
    }

    pub fn collect<C>(self) -> IncludedCollectFuture<'a, T, S, C>
    where
        T: 'static,
        S: 'static,
        S::Target: Clone + 'static,
        C: FromIterator<T> + 'static,
    {
        IncludedCollectFuture {
            select: self.select,
            selection: self.selection,
            _marker: std::marker::PhantomData,
        }
    }
}

pub struct DoubleIncludedSelectExecutor<
    'a,
    T: Model,
    S1: RelationSelection<T>,
    S2: RelationSelection<T>,
> {
    select: SelectExecutor<'a, T>,
    first: S1,
    second: S2,
    _marker: std::marker::PhantomData<(S1, S2)>,
}

impl<'a, T, S1, S2> DoubleIncludedSelectExecutor<'a, T, S1, S2>
where
    T: Model,
    S1: RelationSelection<T>,
    S2: RelationSelection<T>,
{
    pub fn collect<C>(self) -> DoubleIncludedCollectFuture<'a, T, S1, S2, C>
    where
        T: 'static,
        S1: 'static,
        S2: 'static,
        S1::Target: Clone + 'static,
        S2::Target: Clone + 'static,
        C: FromIterator<T> + 'static,
    {
        DoubleIncludedCollectFuture {
            select: self.select,
            first: self.first,
            second: self.second,
            _marker: std::marker::PhantomData,
        }
    }
}

pub struct IncludedCollectFuture<'a, T: Model, S: RelationSelection<T>, C> {
    select: SelectExecutor<'a, T>,
    selection: S,
    _marker: std::marker::PhantomData<C>,
}

pub struct DoubleIncludedCollectFuture<
    'a,
    T: Model,
    S1: RelationSelection<T>,
    S2: RelationSelection<T>,
    C,
> {
    select: SelectExecutor<'a, T>,
    first: S1,
    second: S2,
    _marker: std::marker::PhantomData<C>,
}

impl<
    'a,
    T: Model + 'static + std::marker::Send + std::marker::Sync,
    S: RelationSelection<T> + RelationNestedLoader<'a, T> + std::marker::Send + std::marker::Sync + 'a,
    C: FromIterator<T> + 'static,
> std::future::IntoFuture for IncludedCollectFuture<'a, T, S, C>
where
    S::Target: std::marker::Send + std::marker::Sync,
    S::Via: std::marker::Send + std::marker::Sync,
{
    type Output = crate::Result<C>;
    type IntoFuture =
        std::pin::Pin<Box<dyn std::future::Future<Output = Self::Output> + Send + 'a>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let mut owners = self.select.collect::<Vec<T>>().await?;
            self.select
                .preload_models_with_selection(&mut owners, self.selection)
                .await?;
            Ok(owners.into_iter().collect())
        })
    }
}

impl<
    'a,
    T: Model + 'static + std::marker::Send + std::marker::Sync,
    S1: RelationSelection<T> + RelationNestedLoader<'a, T> + std::marker::Send + std::marker::Sync + 'a,
    S2: RelationSelection<T> + RelationNestedLoader<'a, T> + std::marker::Send + std::marker::Sync + 'a,
    C: FromIterator<T> + 'static,
> std::future::IntoFuture for DoubleIncludedCollectFuture<'a, T, S1, S2, C>
where
    S1::Target: std::marker::Send + std::marker::Sync,
    S1::Via: std::marker::Send + std::marker::Sync,
    S2::Target: std::marker::Send + std::marker::Sync,
    S2::Via: std::marker::Send + std::marker::Sync,
{
    type Output = crate::Result<C>;
    type IntoFuture =
        std::pin::Pin<Box<dyn std::future::Future<Output = Self::Output> + Send + 'a>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let mut owners = self.select.collect::<Vec<T>>().await?;
            self.select
                .preload_models_with_selection(&mut owners, self.first)
                .await?;
            self.select
                .preload_models_with_selection(&mut owners, self.second)
                .await?;
            Ok(owners.into_iter().collect())
        })
    }
}

/// collect_with 的克隆式后端分支(L27:PostgreSQL/MySQL/MSSQL 三份同构
/// 代码收敛):`clone_with_*` → `collect::<Vec<V>>` → 装入对应 Collect 变体。
/// `V` 由变体构造器的期望类型反向推断,宏内无需引用泛型参数。
#[cfg(any(feature = "postgresql", feature = "mysql", feature = "mssql"))]
macro_rules! collect_with_clone_branch {
    ($exec:ident, $f:ident, [$($variant:ident)::+], $clone:ident) => {{
        let future = $exec.$clone().collect::<Vec<_>>();
        $($variant)::+(future, $f, std::marker::PhantomData)
    }};
}

impl<'a, T: Model, V> ProjectionSelectExecutor<'a, T, V> {
    /// 执行查询并收集结果,同时应用转换函数
    /// 用于将查询结果转换为其他类型(如Model)
    /// 示例:collect_with(|v| Uids { id: v })
    // f 仅由本地后端分支消费;clickhouse/influxdb-only 组合下落 Unsupported
    #[cfg_attr(
        not(any(
            feature = "sqlite",
            feature = "postgresql",
            feature = "mysql",
            feature = "mssql",
            feature = "duckdb"
        )),
        allow(unused_variables)
    )]
    pub fn collect_with<C, F, M>(self, f: F) -> ModelCollectWithFuture<'a, T, V, C, M, F>
    where
        T: 'static,
        V: crate::model::FromRowValues + 'static,
        C: FromIterator<M> + 'static,
        F: Fn(V) -> M + Clone + 'static,
        M: 'static,
    {
        match self {
            #[cfg(feature = "sqlite")]
            ProjectionSelectExecutor::Sqlite(exec) => {
                ModelCollectWithFuture::Sqlite(exec.collect_with::<C, F, M>(f))
            }
            // 三个克隆式后端共用同一份组合逻辑(L27)
            #[cfg(feature = "postgresql")]
            ProjectionSelectExecutor::PostgreSQL(exec) => collect_with_clone_branch!(
                exec,
                f,
                [ModelCollectWithFuture::PostgreSQLCollect],
                clone_with_client
            ),
            #[cfg(feature = "mysql")]
            ProjectionSelectExecutor::MySQL(exec) => collect_with_clone_branch!(
                exec,
                f,
                [ModelCollectWithFuture::MySQLCollect],
                clone_with_pool
            ),
            #[cfg(feature = "mssql")]
            ProjectionSelectExecutor::MSSQL(exec) => collect_with_clone_branch!(
                exec,
                f,
                [ModelCollectWithFuture::MSSQLCollect],
                clone_with_pool
            ),
            #[cfg(feature = "duckdb")]
            ProjectionSelectExecutor::DuckDB(exec) => {
                ModelCollectWithFuture::DuckDB(exec.collect_with::<C, F, M>(f))
            }
            #[cfg(feature = "clickhouse")]
            ProjectionSelectExecutor::ClickHouse(_, _) => ModelCollectWithFuture::Unsupported {
                backend: super::super::DbType::ClickHouse,
                feature: "collect_with on ClickHouse; use select_sql",
                _marker: std::marker::PhantomData,
            },
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            ProjectionSelectExecutor::Unsupported {
                backend, feature, ..
            } => ModelCollectWithFuture::Unsupported {
                backend,
                feature,
                _marker: std::marker::PhantomData,
            },
        }
    }
}

impl<'a, T: Model, V> ProjectionSelectExecutor<'a, T, V> {
    fn into_in_filter(self, column: String) -> crate::query::filter::FilterExpr {
        let in_subquery = |subquery: crate::Result<(String, Vec<crate::model::Value>)>| {
            crate::query::filter::FilterExpr::InSubqueryDynamic {
                column,
                subquery: crate::query::filter::DynamicSubquery::new(move |_| subquery.clone()),
            }
        };

        match self {
            #[cfg(feature = "sqlite")]
            ProjectionSelectExecutor::Sqlite(exec) => in_subquery(exec.to_subquery_sql()),
            #[cfg(feature = "postgresql")]
            ProjectionSelectExecutor::PostgreSQL(exec) => in_subquery(exec.to_subquery_sql()),
            #[cfg(feature = "mysql")]
            ProjectionSelectExecutor::MySQL(exec) => in_subquery(exec.to_subquery_sql()),
            #[cfg(feature = "mssql")]
            ProjectionSelectExecutor::MSSQL(exec) => in_subquery(exec.to_subquery_sql()),
            #[cfg(feature = "duckdb")]
            ProjectionSelectExecutor::DuckDB(exec) => in_subquery(exec.to_subquery_sql()),
            #[cfg(feature = "clickhouse")]
            ProjectionSelectExecutor::ClickHouse(_, _) => in_subquery(Err(
                crate::OrmerError::UnsupportedFeature {
                    backend: super::super::DbType::ClickHouse,
                    feature: "subquery on ClickHouse; use select_sql",
                },
            )),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            ProjectionSelectExecutor::Unsupported {
                backend, feature, ..
            } => in_subquery(Err(crate::OrmerError::UnsupportedFeature {
                backend,
                feature,
            })),
        }
    }
}

// 为 ProjectionSelectExecutor 实现 IsInValues trait
impl<'a, T: Model, V: crate::query::builder::ColumnValueType> crate::query::builder::IsInValues<V>
    for ProjectionSelectExecutor<'a, T, V>
{
    fn to_in_expr(self, column: String) -> crate::query::builder::WhereExpr {
        crate::query::builder::WhereExpr::from_filter(self.into_in_filter(column))
    }
}

// 为 &ProjectionSelectExecutor 实现 IsInValues trait(引用版本)
impl<'a, 'b, T: Model, V: crate::query::builder::ColumnValueType>
    crate::query::builder::IsInValues<V> for &'b ProjectionSelectExecutor<'a, T, V>
{
    fn to_in_expr(self, column: String) -> crate::query::builder::WhereExpr {
        crate::query::builder::WhereExpr::from_filter(self.clone().into_in_filter(column))
    }
}

/// 克隆式 collect_with(PostgreSQL/MySQL/MSSQL Collect 变体)的公共
/// 收尾(L27):等待投影结果后逐项应用转换函数,三份同构循环收敛为一份。
/// 后端 Collect 变体只实现 `IntoFuture`,调用方需先 `.into_future()`。
#[cfg(any(feature = "postgresql", feature = "mysql", feature = "mssql"))]
async fn collect_with_map<V, M, C, F, Fut>(future: Fut, mapper: F) -> crate::Result<C>
where
    Fut: Future<Output = crate::Result<Vec<V>>>,
    F: Fn(V) -> M,
    C: FromIterator<M>,
{
    Ok(future.await?.into_iter().map(mapper).collect())
}

impl<'a, T, V, C, M, F> std::future::IntoFuture for ModelCollectWithFuture<'a, T, V, C, M, F>
where
    T: Model + 'static + std::marker::Send + std::marker::Sync,
    V: crate::model::FromRowValues + 'static + std::marker::Send + std::marker::Sync,
    C: FromIterator<M> + 'static,
    M: 'static + std::marker::Send,
    F: Fn(V) -> M + Clone + Send + 'static,
{
    type Output = crate::Result<C>;
    type IntoFuture =
        std::pin::Pin<Box<dyn std::future::Future<Output = Self::Output> + Send + 'a>>;

    fn into_future(self) -> Self::IntoFuture {
        match self {
            #[cfg(feature = "sqlite")]
            ModelCollectWithFuture::Sqlite(future) => Box::pin(future.into_future()),
            // 三个克隆式后端共用同一份 mapper 收尾(L27)
            #[cfg(feature = "postgresql")]
            ModelCollectWithFuture::PostgreSQLCollect(future, mapper, _) => {
                Box::pin(collect_with_map(future.into_future(), mapper))
            }
            #[cfg(feature = "mysql")]
            ModelCollectWithFuture::MySQLCollect(future, mapper, _) => {
                Box::pin(collect_with_map(future.into_future(), mapper))
            }
            #[cfg(feature = "mssql")]
            ModelCollectWithFuture::MSSQLCollect(future, mapper, _) => {
                Box::pin(collect_with_map(future.into_future(), mapper))
            }
            #[cfg(feature = "duckdb")]
            ModelCollectWithFuture::DuckDB(future) => Box::pin(future.into_future()),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            ModelCollectWithFuture::Unsupported {
                backend, feature, ..
            } => Box::pin(async move { Err(unsupported_feature(backend, feature)) }),
        }
    }
}

impl<'a, T> BatchQuery<'a> for SelectExecutor<'a, T>
where
    T: Model + 'static + Send + Sync,
{
    type Output = Vec<T>;

    fn into_batch_future(self) -> BatchQueryFuture<'a, Self::Output> {
        Box::pin(async move { self.collect::<Vec<T>>().await })
    }
}

impl<'a, T> BatchQuery<'a> for FirstFuture<'a, T>
where
    T: Model + 'static + Send + Sync,
{
    type Output = Option<T>;

    fn into_batch_future(self) -> BatchQueryFuture<'a, Self::Output> {
        std::future::IntoFuture::into_future(self)
    }
}

impl<'a, T, R> BatchQuery<'a> for AggregateFuture<'a, T, R>
where
    T: Model + 'static + Send,
    R: crate::model::FromValue + 'static + Send,
{
    type Output = R;

    fn into_batch_future(self) -> BatchQueryFuture<'a, Self::Output> {
        std::future::IntoFuture::into_future(self)
    }
}

impl<'a, R> BatchQuery<'a> for DerivedTableSelectExecutor<'a, R>
where
    R: Model + crate::model::FromRowValues + 'static + Send,
{
    type Output = Vec<R>;

    fn into_batch_future(self) -> BatchQueryFuture<'a, Self::Output> {
        Box::pin(async move { self.collect::<Vec<R>>().await })
    }
}

impl<'a, T> BatchQuery<'a> for RawSelectExecutor<'a, T>
where
    T: crate::model::FromRowValues + 'static + Send,
{
    type Output = Vec<T>;

    fn into_batch_future(self) -> BatchQueryFuture<'a, Self::Output> {
        Box::pin(async move { self.collect::<Vec<T>>().await })
    }
}

impl<'a, T, R> BatchQuery<'a> for RelatedSelectExecutor<'a, T, R>
where
    T: Model + 'static + Send + Sync,
    R: Model + 'static + Send + Sync,
{
    type Output = Vec<T>;

    fn into_batch_future(self) -> BatchQueryFuture<'a, Self::Output> {
        Box::pin(async move { self.collect::<Vec<T>>().await })
    }
}

impl<'a, T, J> BatchQuery<'a> for LeftJoinedSelectExecutor<'a, T, J>
where
    T: Model + 'static + Send + Sync,
    J: Model + 'static + Send + Sync,
{
    type Output = Vec<(T, Option<J>)>;

    fn into_batch_future(self) -> BatchQueryFuture<'a, Self::Output> {
        Box::pin(async move { self.collect::<Vec<(T, Option<J>)>>().await })
    }
}

impl<'a, T, J> BatchQuery<'a> for InnerJoinedSelectExecutor<'a, T, J>
where
    T: Model + 'static + Send + Sync,
    J: Model + 'static + Send + Sync,
{
    type Output = Vec<(T, J)>;

    fn into_batch_future(self) -> BatchQueryFuture<'a, Self::Output> {
        Box::pin(async move { self.collect::<Vec<(T, J)>>().await })
    }
}

impl<'a, T, J> BatchQuery<'a> for RightJoinedSelectExecutor<'a, T, J>
where
    T: Model + 'static + Send + Sync,
    J: Model + 'static + Send + Sync,
{
    type Output = Vec<(Option<T>, J)>;

    fn into_batch_future(self) -> BatchQueryFuture<'a, Self::Output> {
        Box::pin(async move { self.collect::<Vec<(Option<T>, J)>>().await })
    }
}

impl<'a, T, V> BatchQuery<'a> for ProjectionSelectExecutor<'a, T, V>
where
    T: Model + 'static + Send + Sync,
    V: crate::model::FromRowValues + 'static + Send + Sync,
{
    type Output = Vec<V>;

    fn into_batch_future(self) -> BatchQueryFuture<'a, Self::Output> {
        Box::pin(async move { self.collect::<Vec<V>>().await })
    }
}

impl<'a, T, S> BatchQuery<'a> for IncludedSelectExecutor<'a, T, S>
where
    T: Model + 'static + Send + Sync,
    S: RelationSelection<T> + RelationNestedLoader<'a, T> + Send + Sync + 'a + 'static,
    S::Target: Clone + 'static + Send + Sync,
    S::Via: Send + Sync,
{
    type Output = Vec<T>;

    fn into_batch_future(self) -> BatchQueryFuture<'a, Self::Output> {
        Box::pin(async move { self.collect::<Vec<T>>().await })
    }
}

impl<'a, T, S1, S2> BatchQuery<'a> for DoubleIncludedSelectExecutor<'a, T, S1, S2>
where
    T: Model + 'static + Send + Sync,
    S1: RelationSelection<T> + RelationNestedLoader<'a, T> + Send + Sync + 'a + 'static,
    S2: RelationSelection<T> + RelationNestedLoader<'a, T> + Send + Sync + 'a + 'static,
    S1::Target: Clone + 'static + Send + Sync,
    S1::Via: Send + Sync,
    S2::Target: Clone + 'static + Send + Sync,
    S2::Via: Send + Sync,
{
    type Output = Vec<T>;

    fn into_batch_future(self) -> BatchQueryFuture<'a, Self::Output> {
        Box::pin(async move { self.collect::<Vec<T>>().await })
    }
}

/// 统一的 SelectStream 枚举
pub enum SelectStream<'a, T: Model> {
    #[cfg(feature = "sqlite")]
    Sqlite(sqlite_backend::SelectStream<'a, T>),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::SelectStream<'a, T>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::SelectStream<'a, T>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::SelectStream<'a, T>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::SelectStream<'a, T>),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    ClickHouse(
        ClickHouseSelectBackend<'a>,
        crate::query::builder::Select<T>,
    ),
}

impl<'a, T: Model> SelectExecutor<'a, T> {
    /// 创建流式查询执行器
    pub fn stream(self) -> SelectStream<'a, T> {
        match self {
            #[cfg(feature = "sqlite")]
            SelectExecutor::Sqlite(exec) => SelectStream::Sqlite(exec.stream()),
            #[cfg(feature = "postgresql")]
            SelectExecutor::PostgreSQL(exec) => SelectStream::PostgreSQL(exec.stream()),
            #[cfg(feature = "mysql")]
            SelectExecutor::MySQL(exec) => SelectStream::MySQL(exec.stream()),
            #[cfg(feature = "mssql")]
            SelectExecutor::MSSQL(exec) => SelectStream::MSSQL(exec.stream()),
            #[cfg(feature = "duckdb")]
            SelectExecutor::DuckDB(exec) => SelectStream::DuckDB(exec.stream()),
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectExecutor::ClickHouse(db, select) => SelectStream::ClickHouse(db, select),
        }
    }
}

/// 统一的 SelectStreamIterator 枚举
pub enum SelectStreamIterator<'a, T: Model> {
    #[cfg(feature = "sqlite")]
    Sqlite(sqlite_backend::SelectStreamIterator<'a, T>),
    #[cfg(feature = "postgresql")]
    PostgreSQL(postgresql_backend::SelectStreamIterator<'a, T>),
    #[cfg(feature = "mysql")]
    MySQL(mysql_backend::SelectStreamIterator<'a, T>),
    #[cfg(feature = "mssql")]
    MSSQL(mssql_backend::SelectStreamIterator<'a, T>),
    #[cfg(feature = "duckdb")]
    DuckDB(duckdb_backend::SelectStreamIterator<'a, T>),
    #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
    ClickHouse(ClickHouseStreamState<T>, std::marker::PhantomData<&'a ()>),
}

impl<'a, T: Model + 'static> SelectStream<'a, T> {
    /// 返回异步迭代器
    pub async fn into_iter(self) -> crate::Result<SelectStreamIterator<'a, T>> {
        match self {
            #[cfg(feature = "sqlite")]
            SelectStream::Sqlite(stream) => {
                let iter = stream.into_iter().await?;
                Ok(SelectStreamIterator::Sqlite(iter))
            }
            #[cfg(feature = "postgresql")]
            SelectStream::PostgreSQL(stream) => {
                let iter = stream.into_iter().await?;
                Ok(SelectStreamIterator::PostgreSQL(iter))
            }
            #[cfg(feature = "mysql")]
            SelectStream::MySQL(stream) => {
                let iter = stream.into_iter().await?;
                Ok(SelectStreamIterator::MySQL(iter))
            }
            #[cfg(feature = "mssql")]
            SelectStream::MSSQL(stream) => {
                let iter = stream.into_iter().await?;
                Ok(SelectStreamIterator::MSSQL(iter))
            }
            #[cfg(feature = "duckdb")]
            SelectStream::DuckDB(stream) => {
                let iter = stream.into_iter().await?;
                Ok(SelectStreamIterator::DuckDB(iter))
            }
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectStream::ClickHouse(db, select) => {
                // ClickHouse:走 JSONEachRow 字节游标,边拉边解码(真流式);
                // InfluxDB:无游标 API,保持缓冲实现
                #[cfg(feature = "clickhouse")]
                #[cfg_attr(not(feature = "influxdb"), allow(irrefutable_let_patterns))]
                if let ClickHouseSelectBackend::ClickHouse(db) = db {
                    let (sql, params) =
                        select.try_to_sql_with_params(super::super::DbType::ClickHouse)?;
                    let cursor = db.select_json_stream(RawSql::new(sql).with_params(params))?;
                    return Ok(SelectStreamIterator::ClickHouse(
                        ClickHouseStreamState::Streaming(ClickHouseJsonStreamDecoder {
                            cursor,
                            columns: T::columns(),
                            buffer: Vec::new(),
                            finished: false,
                            _marker: std::marker::PhantomData,
                        }),
                        std::marker::PhantomData,
                    ));
                }
                #[cfg(feature = "influxdb")]
                #[allow(irrefutable_let_patterns)]
                if let ClickHouseSelectBackend::Influx(db) = db {
                    let rows = influx_select_models::<T, Vec<T>>(db, select).await?;
                    return Ok(SelectStreamIterator::ClickHouse(
                        ClickHouseStreamState::Buffered(rows.into_iter()),
                        std::marker::PhantomData,
                    ));
                }
                // cfg 门控保证上方两个 if-let 覆盖所有可构造的后端变体;
                // 落到这里只能是手工混用构造的值,返回错误而非 panic。
                Err(crate::OrmerError::invalid_operation(
                    "SelectStream::ClickHouse backend matched neither arm",
                ))
            }
        }
    }
}

/// ClickHouse/InfluxDB 流式迭代器的内部状态(P1-3)。
#[cfg(any(feature = "clickhouse", feature = "influxdb"))]
pub enum ClickHouseStreamState<T: Model> {
    /// InfluxDB 无游标 API:先缓冲全量再逐行吐出(非真流式,
    /// 大结果集有内存压力)。
    Buffered(std::vec::IntoIter<T>),
    /// ClickHouse:包装后端 [`clickhouse_backend::Database::select_json_stream`]
    /// 的字节游标,按行解码 JSONEachRow,内存占用与结果集规模无关。
    #[cfg(feature = "clickhouse")]
    Streaming(ClickHouseJsonStreamDecoder<T>),
}

/// ClickHouse JSONEachRow 字节游标解码器:跨 chunk 维护行缓冲,
/// 每凑齐一行即按列名解码为模型行值。
#[cfg(feature = "clickhouse")]
pub struct ClickHouseJsonStreamDecoder<T: Model> {
    cursor: clickhouse::query::BytesCursor,
    columns: Vec<&'static str>,
    buffer: Vec<u8>,
    finished: bool,
    _marker: std::marker::PhantomData<T>,
}

#[cfg(feature = "clickhouse")]
impl<T: Model> ClickHouseJsonStreamDecoder<T> {
    async fn next_row(&mut self) -> Option<crate::Result<T>> {
        loop {
            if let Some(pos) = self.buffer.iter().position(|&byte| byte == b'\n') {
                let line: Vec<u8> = self.buffer.drain(..=pos).collect();
                let line = String::from_utf8_lossy(&line[..line.len() - 1]).into_owned();
                if line.trim().is_empty() {
                    continue;
                }
                let row: serde_json::Value = match serde_json::from_str(&line) {
                    Ok(row) => row,
                    Err(error) => {
                        return Some(Err(crate::ormer_error!(
                            "Invalid ClickHouse JSONEachRow row: {error}"
                        )))
                    }
                };
                let values = match super::super::clickhouse_backend::named_json_row_values(
                    &row,
                    &self.columns,
                ) {
                    Ok(values) => values,
                    Err(error) => return Some(Err(error)),
                };
                return Some(T::from_row_values(&values));
            }
            if self.finished {
                return None;
            }
            match self.cursor.next().await {
                Ok(Some(chunk)) => self.buffer.extend_from_slice(&chunk),
                Ok(None) => {
                    self.finished = true;
                }
                Err(error) => {
                    self.finished = true;
                    return Some(Err(crate::OrmerError::from_external(
                        "clickhouse::BytesCursor::next",
                        error,
                    )));
                }
            }
        }
    }
}

impl<'a, T: Model + 'static> SelectStreamIterator<'a, T> {
    /// 获取下一行数据
    pub async fn next(&mut self) -> Option<crate::Result<T>> {
        match self {
            #[cfg(feature = "sqlite")]
            SelectStreamIterator::Sqlite(iter) => iter.next().await,
            #[cfg(feature = "postgresql")]
            SelectStreamIterator::PostgreSQL(iter) => iter.next().await,
            #[cfg(feature = "mysql")]
            SelectStreamIterator::MySQL(iter) => iter.next().await,
            #[cfg(feature = "mssql")]
            SelectStreamIterator::MSSQL(iter) => iter.next().await,
            #[cfg(feature = "duckdb")]
            SelectStreamIterator::DuckDB(iter) => iter.next().await,
            #[cfg(any(feature = "clickhouse", feature = "influxdb"))]
            SelectStreamIterator::ClickHouse(state, _) => match state {
                ClickHouseStreamState::Buffered(rows) => rows.next().map(Ok),
                #[cfg(feature = "clickhouse")]
                ClickHouseStreamState::Streaming(decoder) => decoder.next_row().await,
            },
        }
    }
}