yang-db 0.2.0

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

/// 将 SqlValue 绑定到 sqlx 查询的内部宏(PostgreSQL)
///
/// 封装 SqlValue 各变体到 `.bind()` 调用的映射逻辑,消除 4 个 bind_param
/// 函数中完全相同的 match 分支重复代码。未来新增 SqlValue 变体时,
/// 只需在此宏中添加一个分支即可完成所有函数的更新。
///
/// 与 MySQL 后端的差异:
/// - JSON 直接绑定原生 `serde_json::Value`(sqlx 的 `json` feature 已开启,
///   映射到 PostgreSQL 的 `JSON`/`JSONB`),而非序列化为字符串。
/// - Bytes 绑定 `Vec<u8>`(映射到 `BYTEA`)。
///
/// # 参数
/// - `$query`: sqlx 查询对象(支持 `.bind()` 方法的任意类型)
/// - `$param`: `&SqlValue` 引用
///
/// # 返回
/// 绑定参数后的查询对象(与 `$query` 类型相同)
macro_rules! bind_value_match {
    ($query:expr, $param:expr) => {
        match $param {
            // NULL 值:绑定为 Option<i32>::None
            SqlValue::Null => $query.bind(Option::<i32>::None),
            // 布尔值
            SqlValue::Bool(b) => $query.bind(*b),
            // 整数
            SqlValue::Int(i) => $query.bind(*i),
            // 浮点数
            SqlValue::Float(f) => $query.bind(*f),
            // 字符串(需要 clone 以满足 sqlx 的所有权要求)
            SqlValue::String(s) => $query.bind(s.clone()),
            // 字节数组(BYTEA,需要 clone)
            SqlValue::Bytes(b) => $query.bind(b.clone()),
            // JSON 值:绑定原生 serde_json::Value(JSON/JSONB)
            SqlValue::Json(j) => $query.bind(j.clone()),
            // 日期时间
            SqlValue::DateTime(dt) => $query.bind(*dt),
            // 时间戳(整数)
            SqlValue::Timestamp(ts) => $query.bind(*ts),
        }
    };
}

/// 批量插入的默认批次大小
///
/// 为了避免单次插入过多数据导致 SQL 语句过大或超时,
/// 批量插入操作会自动将数据分批处理,每批最多插入 INSERT_BATCH_SIZE 条记录。
const INSERT_BATCH_SIZE: usize = 500;

/// 批量更新的默认批次大小
const UPDATE_BATCH_SIZE: usize = 1000;

/// 协议层单语句绑定占位符上限。
///
/// MySQL 二进制协议预编译语句占位符上限为 2^16-1;PostgreSQL Bind 消息的
/// 参数计数同为 Int16,上限一致。
const MAX_BIND_PARAMS: usize = 65_535;

/// 由「非主键列数」推导 CASE WHEN 批量更新的安全批大小(与 MySQL 侧同口径)。
fn derive_update_batch_size(field_count: usize, requested: usize) -> usize {
    let per_record = field_count.saturating_mul(2).saturating_add(1);
    if per_record == 0 {
        return requested;
    }
    (MAX_BIND_PARAMS / per_record).max(1).min(requested)
}

/// 取首条记录的「非主键列数」,与 build_update_batch 的 update_fields 口径一致。
fn update_field_count(records: &[serde_json::Value], where_field: &str) -> usize {
    records
        .first()
        .and_then(|r| r.as_object())
        .map(|obj| obj.keys().filter(|k| k.as_str() != where_field).count())
        .unwrap_or(0)
}

/// 压入一个参数并返回其 PostgreSQL 占位符(`$N`,1 基)
///
/// PostgreSQL 使用编号占位符,编号由参数压入后的 `params.len()` 决定,
/// 保证占位符编号与最终绑定顺序严格一致。这是与 MySQL 后端(统一使用 `?`)
/// 的核心方言差异,在手写 INSERT/UPDATE/UPSERT 等 SQL 时集中通过本助手处理。
fn push_placeholder(params: &mut Vec<SqlValue>, value: SqlValue) -> String {
    params.push(value);
    format!("${}", params.len())
}

/// SQL 生成器(内部使用)
#[allow(dead_code)]
pub(crate) struct SqlGenerator {
    /// 生成的 SQL 语句
    sql: String,
    /// SQL 参数列表
    params: Vec<SqlValue>,
}

#[allow(dead_code)]
impl SqlGenerator {
    /// 创建新的 SQL 生成器
    ///
    /// 预分配合理的缓冲区容量,减少 SQL 字符串构建过程中的重新分配次数:
    /// - `sql` 预分配 256 字节,适合大多数 SQL 语句
    /// - `params` 预分配 8 个槽位,适合大多数查询参数数量
    pub(crate) fn new() -> Self {
        Self {
            // 预分配 256 字节,减少字符串扩容次数
            sql: String::with_capacity(256),
            // 预分配 8 个参数槽位,减少 Vec 扩容次数
            params: Vec::with_capacity(8),
        }
    }

    /// 获取生成的 SQL 语句
    pub(crate) fn get_sql(&self) -> &str {
        &self.sql
    }

    /// 获取参数列表
    pub(crate) fn get_params(&self) -> &[SqlValue] {
        &self.params
    }

    /// 添加 SQL 片段
    fn append(&mut self, fragment: &str) {
        self.sql.push_str(fragment);
    }

    /// 添加参数
    fn add_param(&mut self, param: SqlValue) {
        self.params.push(param);
    }

    fn append_condition(&mut self, condition: Condition) -> Result<(), crate::error::DbError> {
        let rendered =
            crate::postgres::condition::render_condition_checked(condition, self.params.len())?;
        self.sql.push_str(&rendered.sql);
        self.params.extend(rendered.params);
        Ok(())
    }

    /// 清空生成器(保留已分配容量,避免重复分配)
    fn clear(&mut self) {
        self.sql.clear();
        self.params.clear();
    }

    /// 测试专用:暴露 clear 方法供测试模块调用
    #[cfg(test)]
    pub(crate) fn clear_for_test(&mut self) {
        self.clear();
    }

    /// 测试专用:获取 sql 字段的当前容量
    #[cfg(test)]
    pub(crate) fn sql_capacity(&self) -> usize {
        self.sql.capacity()
    }

    /// 测试专用:获取 params 字段的当前容量
    #[cfg(test)]
    pub(crate) fn params_capacity(&self) -> usize {
        self.params.capacity()
    }

    /// 生成 SELECT 语句
    ///
    /// # 参数
    /// - builder: QueryBuilder 引用
    ///
    /// # 返回
    /// - Ok(()): 成功生成 SQL
    /// - Err(DbError): 生成失败
    fn build_select(&mut self, builder: &QueryBuilder) -> Result<(), crate::error::DbError> {
        self.clear();
        self.build_compound_select(builder)
    }

    fn build_compound_select(
        &mut self,
        builder: &QueryBuilder,
    ) -> Result<(), crate::error::DbError> {
        // SELECT 子句
        self.append("SELECT ");

        // DISTINCT 关键字
        if builder.distinct {
            self.append("DISTINCT ");
        }

        // 字段列表
        if builder.fields.is_empty() {
            self.append("*");
        } else {
            // 验证需求: ID-1 — field() 按设计接受 SQL 表达式,标识符转义由调用方负责
            self.append(&builder.fields.join(", "));
        }

        // FROM 子句
        self.append(" FROM ");
        self.append(&super::identifier::quote_identifier(&builder.table)?);

        // JOIN 子句
        if !builder.joins.is_empty() {
            self.build_joins(&builder.joins)?;
        }

        // WHERE 子句
        if !builder.conditions.is_empty() {
            self.build_where(&builder.conditions)?;
        }

        // GROUP BY 子句
        if !builder.group_by.is_empty() {
            self.build_group_by(&builder.group_by);
        }

        // HAVING 子句
        if !builder.having_clause.is_empty() {
            if builder.group_by.is_empty() {
                return Err(crate::error::DbError::MissingGroupByClause);
            }
            self.build_having(&builder.having_clause)?;
        }

        for (operator, branch) in &builder.unions {
            match operator {
                UnionOperator::Distinct => self.append(" UNION "),
                UnionOperator::All => self.append(" UNION ALL "),
            }
            self.append("(");
            self.build_compound_select(branch)?;
            self.append(")");
        }

        // 当前构建器的 ORDER/LIMIT 作用于整个复合查询;分支自己的作用域保留在括号内。
        if !builder.order_by.is_empty() {
            self.build_order_by(&builder.order_by);
        }

        // LIMIT 子句
        if let Some(limit) = builder.limit {
            self.append(" LIMIT ");
            self.append(&limit.to_string());
        }

        // OFFSET 子句
        if let Some(offset) = builder.offset {
            self.append(" OFFSET ");
            self.append(&offset.to_string());
        }

        Ok(())
    }

    /// 生成 WHERE 子句
    ///
    /// 委托给 [`condition_to_sql_owned`](已生成 PostgreSQL 风格的 `$N` 占位符,
    /// 编号基于 `self.params` 当前长度自动接续)。
    ///
    /// # 参数
    /// - conditions: 条件列表
    ///
    /// # 返回
    /// - Ok(()): 成功生成 WHERE 子句
    /// - Err(DbError): 生成失败
    fn build_where(&mut self, conditions: &[Condition]) -> Result<(), crate::error::DbError> {
        if conditions.is_empty() {
            return Ok(());
        }

        self.append(" WHERE ");

        if conditions.len() == 1 {
            self.append_condition(conditions[0].clone())?;
        } else {
            // 内联拼接:逐条 append_condition 直接写入 self.sql,省去 to_vec() 容器 +
            // Condition::And 包装 + parts Vec;注意条件树仍按值消费,每个条件在
            // append_condition 处 clone 一次(见 :277/:286)。
            self.sql.push('(');
            for (i, cond) in conditions.iter().enumerate() {
                if i > 0 {
                    self.sql.push_str(" AND ");
                }
                self.append_condition(cond.clone())?;
            }
            self.sql.push(')');
        }

        Ok(())
    }

    /// 生成 JOIN 子句
    ///
    /// # 参数
    /// - joins: JOIN 子句列表
    ///
    /// 注意:`join.table` 是已校验的标识符原文(渲染期经 `quote_identifier` 校验+转义),
    /// `join.on` 按设计接受原始 SQL 表达式。
    fn build_joins(&mut self, joins: &[JoinClause]) -> Result<(), crate::error::DbError> {
        use crate::postgres::field::JoinType;

        for join in joins {
            let join_type_str = match join.join_type {
                JoinType::Inner => " INNER JOIN ",
                JoinType::Left => " LEFT JOIN ",
                JoinType::Right => " RIGHT JOIN ",
            };

            self.append(join_type_str);
            self.append(&super::identifier::quote_identifier(&join.table)?);
            self.append(" ON ");
            self.append(&join.on);
        }

        Ok(())
    }

    /// 生成 ORDER BY 子句
    ///
    /// # 参数
    /// - orders: 排序子句列表
    ///
    /// 注意:`order.field` 按设计接受原始 SQL 表达式(与 MySQL 设计一致),
    /// 标识符转义由调用方负责。
    fn build_order_by(&mut self, orders: &[OrderClause]) {
        if orders.is_empty() {
            return;
        }

        self.append(" ORDER BY ");

        // 直接 push_str 写入 self.sql,避免先 collect Vec<String> 再 join 的中间分配。
        for (i, order) in orders.iter().enumerate() {
            if i > 0 {
                self.sql.push_str(", ");
            }
            self.sql.push_str(&order.field);
            self.sql.push(' ');
            self.sql.push_str(if order.asc { "ASC" } else { "DESC" });
        }
    }

    /// 生成 GROUP BY 子句
    ///
    /// # 参数
    /// - groups: 分组字段列表
    ///
    /// 注意:分组字段按设计接受原始 SQL 表达式(与 MySQL 设计一致),
    /// 标识符转义由调用方负责。
    fn build_group_by(&mut self, groups: &[String]) {
        if groups.is_empty() {
            return;
        }

        self.append(" GROUP BY ");
        self.append(&groups.join(", "));
    }

    /// 生成 HAVING 子句
    fn build_having(&mut self, conditions: &[Condition]) -> Result<(), crate::error::DbError> {
        self.append(" HAVING ");
        if conditions.len() == 1 {
            self.append_condition(conditions[0].clone())?;
        } else {
            // 直接 push_str 写入 self.sql,避免先 collect Vec<String> 再 join。
            // 先把片段存入局部变量结束对 self.params 的可变借用,再 push_str 到 self.sql。
            // 占位符编号由 condition 模块基于 self.params 当前长度推导,跨片段连续。
            for (i, c) in conditions.iter().enumerate() {
                if i > 0 {
                    self.sql.push_str(" AND ");
                }
                self.append_condition(c.clone())?;
            }
        }
        Ok(())
    }

    /// 生成 INSERT 语句
    ///
    /// 占位符使用 PostgreSQL 风格的 `$N`,编号在压入参数后按 `params.len()` 推导。
    /// 当某字段值为 `SqlValue::Null` 时,直接在 SQL 中内联字面量 `NULL` 而不压入参数
    /// (PostgreSQL 拒绝未带类型的绑定 NULL 对非整型列赋值,故 NULL 不占用占位符编号)。
    ///
    /// # 参数
    /// - table: 表名
    /// - data: 要插入的数据(JSON 格式)
    /// - field_types: 字段类型映射
    ///
    /// # 返回
    /// - Ok(()): 成功生成 SQL
    /// - Err(DbError): 生成失败
    pub(crate) fn build_insert(
        &mut self,
        table: &str,
        data: &serde_json::Value,
        field_types: &HashMap<String, FieldType>,
    ) -> Result<(), crate::error::DbError> {
        // 清空之前的内容
        self.clear();

        // 确保 data 是一个对象
        let obj = data.as_object().ok_or_else(|| {
            crate::error::DbError::SerializationError("插入数据必须是 JSON 对象".to_string())
        })?;

        if obj.is_empty() {
            return Err(crate::error::DbError::SerializationError(
                "插入数据不能为空".to_string(),
            ));
        }

        // 提取字段名和占位符(列名经 quote_identifier 校验+转义;DB-1)
        let mut fields = Vec::with_capacity(obj.len());
        let mut placeholders = Vec::with_capacity(obj.len());

        for (key, value) in obj.iter() {
            fields.push(super::identifier::quote_identifier(key)?);

            // 根据字段类型转换值
            let sql_value = self.json_value_to_sql_value(value, field_types.get(key))?;
            // NULL 内联字面量,不占占位符编号;其余压入并生成 $N
            match sql_value {
                SqlValue::Null => placeholders.push("NULL".to_string()),
                v => placeholders.push(push_placeholder(&mut self.params, v)),
            }
        }

        // 构建 INSERT 语句(表名 quote)
        self.append("INSERT INTO ");
        self.append(&super::identifier::quote_identifier(table)?);
        self.append(" (");
        self.append(&fields.join(", "));
        self.append(") VALUES (");
        self.append(&placeholders.join(", "));
        self.append(")");

        Ok(())
    }
    /// 生成批量 INSERT 语句(PostgreSQL)
    ///
    /// 占位符使用 `$N`,编号按参数压入顺序连续递增。NULL 值内联字面量 `NULL`,
    /// 不占用占位符编号(PostgreSQL 拒绝未类型化的绑定 NULL)。
    pub(crate) fn build_insert_batch(
        &mut self,
        table: &str,
        data_list: &[serde_json::Value],
        field_types: &HashMap<String, FieldType>,
    ) -> Result<(), crate::error::DbError> {
        self.clear();

        if data_list.is_empty() {
            return Err(crate::error::DbError::SerializationError(
                "批量插入数据不能为空".to_string(),
            ));
        }

        let first_obj = data_list[0].as_object().ok_or_else(|| {
            crate::error::DbError::SerializationError("插入数据必须是 JSON 对象".to_string())
        })?;

        if first_obj.is_empty() {
            return Err(crate::error::DbError::SerializationError(
                "插入数据不能为空".to_string(),
            ));
        }

        let fields: Vec<String> = first_obj.keys().cloned().collect();

        // 列集一致性校验(NEW-9):见 MySQL 同名方法,异构记录会静默丢列 / 填 NULL。
        for (idx, data) in data_list.iter().enumerate().skip(1) {
            let obj = data.as_object().ok_or_else(|| {
                crate::error::DbError::SerializationError("插入数据必须是 JSON 对象".to_string())
            })?;
            if obj.len() != fields.len() || !fields.iter().all(|f| obj.contains_key(f)) {
                return Err(crate::error::DbError::InvalidArgument(format!(
                    "批量插入第 {idx} 条记录的列集与首条不一致"
                )));
            }
        }

        // 表名与列头 quote(DB-1);fields 保留原始键用于 obj.get 查值。
        let quoted_fields: Result<Vec<String>, crate::error::DbError> = fields
            .iter()
            .map(|f| super::identifier::quote_identifier(f))
            .collect();
        let quoted_fields = quoted_fields?;
        self.append("INSERT INTO ");
        self.append(&super::identifier::quote_identifier(table)?);
        self.append(" (");
        self.append(&quoted_fields.join(", "));
        self.append(") VALUES ");
        for (record_idx, data) in data_list.iter().enumerate() {
            if record_idx > 0 {
                self.sql.push_str(", ");
            }

            let obj = data.as_object().ok_or_else(|| {
                crate::error::DbError::SerializationError("插入数据必须是 JSON 对象".to_string())
            })?;

            self.sql.push('(');
            for (field_idx, field) in fields.iter().enumerate() {
                if field_idx > 0 {
                    self.sql.push_str(", ");
                }
                let value = obj.get(field).unwrap_or(&serde_json::Value::Null);
                let sql_value = self.json_value_to_sql_value(value, field_types.get(field))?;
                match sql_value {
                    // NULL 内联字面量,不占占位符编号
                    SqlValue::Null => self.sql.push_str("NULL"),
                    v => {
                        let ph = push_placeholder(&mut self.params, v);
                        self.sql.push_str(&ph);
                    }
                }
            }
            self.sql.push(')');
        }
        Ok(())
    }
    /// 生成 UPDATE 语句(PostgreSQL)
    ///
    /// SET 子句先压入参数生成 `$1..$k`,随后 WHERE 子句的占位符编号自动接续
    /// (`build_where` 委托的 condition 模块基于 `self.params` 当前长度推导)。
    pub(crate) fn build_update(
        &mut self,
        table: &str,
        data: &serde_json::Value,
        field_types: &HashMap<String, FieldType>,
        conditions: &[Condition],
    ) -> Result<(), crate::error::DbError> {
        self.clear();

        if conditions.is_empty() {
            return Err(crate::error::DbError::MissingWhereClause);
        }

        let obj = data.as_object().ok_or_else(|| {
            crate::error::DbError::SerializationError("更新数据必须是 JSON 对象".to_string())
        })?;

        if obj.is_empty() {
            return Err(crate::error::DbError::SerializationError(
                "更新数据不能为空".to_string(),
            ));
        }

        self.append("UPDATE ");
        self.append(&super::identifier::quote_identifier(table)?);
        self.append(" SET ");

        // 逐字段生成 `字段 = $N`;值为 NULL 时内联字面量 NULL(不占占位符编号),
        // 与 build_insert/build_update_batch/build_upsert 一致。PG 对未类型化绑定的
        // NULL 默认按 INT4,对 text/timestamp 等列 SET col=$1 绑 NULL 会报类型不匹配(DB-3)。
        // 列名经 quote_identifier 校验+转义(DB-1)。
        for (i, (key, value)) in obj.iter().enumerate() {
            if i > 0 {
                self.sql.push_str(", ");
            }
            let sql_value = self.json_value_to_sql_value(value, field_types.get(key))?;
            self.sql
                .push_str(&super::identifier::quote_identifier(key)?);
            self.sql.push_str(" = ");
            match sql_value {
                SqlValue::Null => self.sql.push_str("NULL"),
                v => {
                    let ph = push_placeholder(&mut self.params, v);
                    self.sql.push_str(&ph);
                }
            }
        }

        // WHERE 子句的占位符编号接续 SET 子句已压入的参数
        self.build_where(conditions)?;

        Ok(())
    }

    /// 生成受控的字段原子加减 UPDATE。
    pub(crate) fn build_arithmetic_update(
        &mut self,
        table: &str,
        field: &str,
        operator: ArithmeticOperator,
        amount: i64,
        conditions: &[Condition],
    ) -> Result<(), crate::error::DbError> {
        self.clear();
        if conditions.is_empty() {
            return Err(crate::error::DbError::MissingWhereClause);
        }
        let table = super::identifier::quote_identifier(table)?;
        let field = super::identifier::quote_identifier(field)?;
        self.sql.push_str("UPDATE ");
        self.sql.push_str(&table);
        self.sql.push_str(" SET ");
        self.sql.push_str(&field);
        self.sql.push_str(" = ");
        self.sql.push_str(&field);
        self.sql.push(' ');
        self.sql.push_str(operator.as_sql());
        self.sql.push(' ');
        let placeholder = push_placeholder(&mut self.params, SqlValue::Int(amount));
        self.sql.push_str(&placeholder);
        self.build_where(conditions)
    }

    /// 生成 DELETE 语句(PostgreSQL)
    pub(crate) fn build_delete(
        &mut self,
        table: &str,
        conditions: &[Condition],
    ) -> Result<(), crate::error::DbError> {
        self.clear();

        if conditions.is_empty() {
            return Err(crate::error::DbError::MissingWhereClause);
        }

        self.append("DELETE FROM ");
        self.append(&super::identifier::quote_identifier(table)?);
        self.build_where(conditions)?;

        Ok(())
    }

    /// 生成批量 UPDATE 语句(PostgreSQL,CASE WHEN 策略)
    ///
    /// 与 MySQL 后端结构一致,差异在占位符方言:`WHEN id=$N THEN $M` 及
    /// `WHERE id IN ($K, ...)` 的编号均在压入参数后按 `params.len()` 推导。
    /// 任意值为 `SqlValue::Null` 时内联字面量 `NULL`(不占占位符编号),
    /// 规避 PostgreSQL 对未类型化绑定 NULL 的限制。
    pub(crate) fn build_update_batch(
        &mut self,
        table: &str,
        records: &[serde_json::Value],
        id_field: &str,
        field_types: &std::collections::HashMap<String, FieldType>,
    ) -> Result<(), crate::error::DbError> {
        self.clear();

        if records.is_empty() {
            return Err(crate::error::DbError::SerializationError(
                "批量更新数据不能为空".to_string(),
            ));
        }

        let first = records[0].as_object().ok_or_else(|| {
            crate::error::DbError::SerializationError("更新数据必须是 JSON 对象".to_string())
        })?;

        // 收集需要更新的字段名(排除主键字段)
        let update_fields: Vec<String> = first
            .keys()
            .filter(|k| k.as_str() != id_field)
            .cloned()
            .collect();

        if update_fields.is_empty() {
            return Err(crate::error::DbError::SerializationError(
                "没有可更新的字段".to_string(),
            ));
        }

        // 列集一致性校验(NEW-9):见 MySQL 同名方法。
        for (idx, record) in records.iter().enumerate() {
            let obj = record.as_object().ok_or_else(|| {
                crate::error::DbError::SerializationError("更新数据必须是 JSON 对象".to_string())
            })?;
            if !obj.contains_key(id_field) {
                return Err(crate::error::DbError::InvalidArgument(format!(
                    "批量更新第 {idx} 条记录缺少主键字段 {id_field}"
                )));
            }
            let non_id_len = obj.keys().filter(|k| k.as_str() != id_field).count();
            if non_id_len != update_fields.len()
                || !update_fields.iter().all(|f| obj.contains_key(f))
            {
                return Err(crate::error::DbError::InvalidArgument(format!(
                    "批量更新第 {idx} 条记录的列集与首条不一致"
                )));
            }
        }

        // 表名 quote(DB-1);id_field/列名在各发射点 quote,原始值保留用于 record.get。
        let quoted_id = super::identifier::quote_identifier(id_field)?;
        self.sql.push_str("UPDATE ");
        self.sql
            .push_str(&super::identifier::quote_identifier(table)?);
        self.sql.push_str(" SET ");

        // 为每个字段生成 CASE WHEN 子句
        for (field_idx, field) in update_fields.iter().enumerate() {
            if field_idx > 0 {
                self.sql.push_str(", ");
            }
            self.sql
                .push_str(&super::identifier::quote_identifier(field)?);
            self.sql.push_str(" = CASE ");

            for record in records {
                let id_val = record.get(id_field).unwrap_or(&serde_json::Value::Null);
                let field_val = record
                    .get(field.as_str())
                    .unwrap_or(&serde_json::Value::Null);

                let id_sql_val = self.json_value_to_sql_value(id_val, field_types.get(id_field))?;
                let field_sql_val =
                    self.json_value_to_sql_value(field_val, field_types.get(field.as_str()))?;

                // WHEN id=$N THEN $M(值位置 NULL 内联,不占编号)
                self.sql.push_str("WHEN ");
                self.sql.push_str(&quoted_id);
                self.sql.push('=');
                match id_sql_val {
                    SqlValue::Null => self.sql.push_str("NULL"),
                    v => {
                        let ph = push_placeholder(&mut self.params, v);
                        self.sql.push_str(&ph);
                    }
                }
                self.sql.push_str(" THEN ");
                match field_sql_val {
                    SqlValue::Null => self.sql.push_str("NULL"),
                    v => {
                        let ph = push_placeholder(&mut self.params, v);
                        self.sql.push_str(&ph);
                    }
                }
                self.sql.push(' ');
            }

            self.sql.push_str("END");
        }

        // 生成 WHERE id IN ($K, ...) 子句
        self.sql.push_str(" WHERE ");
        self.sql.push_str(&quoted_id);
        self.sql.push_str(" IN (");

        for (idx, record) in records.iter().enumerate() {
            if idx > 0 {
                self.sql.push(',');
            }
            let id_val = record.get(id_field).unwrap_or(&serde_json::Value::Null);
            let id_sql_val = self.json_value_to_sql_value(id_val, field_types.get(id_field))?;
            match id_sql_val {
                SqlValue::Null => self.sql.push_str("NULL"),
                v => {
                    let ph = push_placeholder(&mut self.params, v);
                    self.sql.push_str(&ph);
                }
            }
        }

        self.sql.push(')');

        Ok(())
    }
    /// 生成 UPSERT 语句(PostgreSQL `INSERT ... ON CONFLICT ... DO UPDATE`)
    ///
    /// 与 MySQL 的 `ON DUPLICATE KEY UPDATE` 的核心差异:PostgreSQL 必须显式指定
    /// 冲突目标列(`conflict_columns`),并用 `EXCLUDED.col` 引用待插入的新值。
    /// 当 `conflict_columns` 为空时回退为 `ON CONFLICT DO NOTHING`(无冲突目标,
    /// 仅在任意约束冲突时跳过)。冲突目标列本身不出现在 DO UPDATE 的 SET 列表中。
    pub(crate) fn build_upsert(
        &mut self,
        table: &str,
        data: &serde_json::Value,
        field_types: &HashMap<String, FieldType>,
        conflict_columns: &[String],
    ) -> Result<(), crate::error::DbError> {
        self.clear();

        let obj = data.as_object().ok_or_else(|| {
            crate::error::DbError::SerializationError("插入数据必须是 JSON 对象".to_string())
        })?;

        if obj.is_empty() {
            return Err(crate::error::DbError::SerializationError(
                "插入数据不能为空".to_string(),
            ));
        }

        let fields: Vec<String> = obj.keys().cloned().collect();
        // 列名/表名 quote(DB-1);fields 保留原始键用于 obj.get 查值与冲突列比较。
        let quoted_fields: Result<Vec<String>, crate::error::DbError> = fields
            .iter()
            .map(|f| super::identifier::quote_identifier(f))
            .collect();
        let quoted_fields = quoted_fields?;

        self.sql.push_str("INSERT INTO ");
        self.sql
            .push_str(&super::identifier::quote_identifier(table)?);
        self.sql.push_str(" (");
        self.sql.push_str(&quoted_fields.join(", "));
        self.sql.push_str(") VALUES (");

        for (i, field) in fields.iter().enumerate() {
            if i > 0 {
                self.sql.push_str(", ");
            }
            let val = obj.get(field.as_str()).unwrap_or(&serde_json::Value::Null);
            let sql_value = self.json_value_to_sql_value(val, field_types.get(field.as_str()))?;
            match sql_value {
                SqlValue::Null => self.sql.push_str("NULL"),
                v => {
                    let ph = push_placeholder(&mut self.params, v);
                    self.sql.push_str(&ph);
                }
            }
        }
        self.sql.push(')');

        if conflict_columns.is_empty() {
            // 无显式冲突目标:任意约束冲突时跳过插入
            self.sql.push_str(" ON CONFLICT DO NOTHING");
            return Ok(());
        }

        // 冲突目标列 quote
        let quoted_conflict: Result<Vec<String>, crate::error::DbError> = conflict_columns
            .iter()
            .map(|c| super::identifier::quote_identifier(c))
            .collect();
        let quoted_conflict = quoted_conflict?;
        self.sql.push_str(" ON CONFLICT (");
        self.sql.push_str(&quoted_conflict.join(", "));
        self.sql.push_str(") DO UPDATE SET ");

        // 冲突目标列不参与更新,其余列用 EXCLUDED.col 取待插入的新值
        let mut first = true;
        for (idx, f) in fields.iter().enumerate() {
            if conflict_columns.iter().any(|c| c == f) {
                continue;
            }
            if !first {
                self.sql.push_str(", ");
            }
            first = false;
            let qf = &quoted_fields[idx];
            self.sql.push_str(qf);
            self.sql.push_str(" = EXCLUDED.");
            self.sql.push_str(qf);
        }

        // 所有列都是冲突目标列时 SET 列表为空,会导致语法错误;
        // 退化为对首个冲突列做恒等更新(col = EXCLUDED.col),保证语句合法。
        if first {
            let first_conflict = &quoted_conflict[0];
            self.sql.push_str(first_conflict);
            self.sql.push_str(" = EXCLUDED.");
            self.sql.push_str(first_conflict);
        }

        Ok(())
    }

    /// 将 JSON 值转换为 SqlValue(PostgreSQL)
    ///
    /// 与 MySQL 后端逻辑一致:字段类型标记优先,其余按 JSON 原生类型推断。
    /// 数组 / 对象映射为 `SqlValue::Json`(PostgreSQL JSON/JSONB),而非字符串。
    fn json_value_to_sql_value(
        &self,
        value: &serde_json::Value,
        field_type: Option<&FieldType>,
    ) -> Result<SqlValue, crate::error::DbError> {
        use serde_json::Value;

        if let Some(ft) = field_type {
            match ft {
                FieldType::Json => return Ok(SqlValue::Json(value.clone())),
                FieldType::DateTime => {
                    if let Some(s) = value.as_str() {
                        let dt = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S")
                            .map_err(|e| {
                                crate::error::DbError::TypeConversionError(format!(
                                    "无法解析 DATETIME 字符串: {}",
                                    e
                                ))
                            })?;
                        return Ok(SqlValue::DateTime(dt));
                    } else if value.is_null() {
                        return Ok(SqlValue::Null);
                    } else {
                        // 值形态不匹配类型提示:显式报错而非静默跌穿到默认转换(NEW-10)
                        return Err(crate::error::DbError::TypeConversionError(format!(
                            "DateTime 字段期望字符串,实得 {value}"
                        )));
                    }
                }
                FieldType::Timestamp => {
                    if let Some(i) = value.as_i64() {
                        return Ok(SqlValue::Timestamp(i));
                    } else if value.is_null() {
                        return Ok(SqlValue::Null);
                    } else {
                        return Err(crate::error::DbError::TypeConversionError(format!(
                            "Timestamp 字段期望整数,实得 {value}"
                        )));
                    }
                }
                FieldType::Decimal => {
                    // DECIMAL/NUMERIC:见 MySQL 同名分支(NG-3)。仅当值能被 f64 精确
                    // 表示(|v| < 2^53)才走 Float;超出/高精度降级字符串,PG 隐式转换保精度。
                    const SAFE_INT: f64 = 9_007_199_254_740_992.0; // 2^53
                    if let Some(i) = value.as_i64() {
                        if (i.unsigned_abs() as f64) < SAFE_INT {
                            return Ok(SqlValue::Float(i as f64));
                        }
                        return Ok(SqlValue::String(i.to_string()));
                    }
                    if let Some(f) = value.as_f64() {
                        if f.is_finite() && f.abs() < SAFE_INT {
                            return Ok(SqlValue::Float(f));
                        }
                    }
                    if value.is_null() {
                        return Ok(SqlValue::Null);
                    }
                    if value.is_number() {
                        return Ok(SqlValue::String(value.to_string()));
                    }
                    if let Some(s) = value.as_str() {
                        return Ok(SqlValue::String(s.to_string()));
                    }
                    return Err(crate::error::DbError::TypeConversionError(format!(
                        "Decimal 字段期望数字或数字字符串,实得 {value}"
                    )));
                }
                FieldType::Blob => {
                    if let Some(s) = value.as_str() {
                        use base64::Engine;
                        if let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(s) {
                            return Ok(SqlValue::Bytes(bytes));
                        }
                        return Ok(SqlValue::Bytes(s.as_bytes().to_vec()));
                    } else if value.is_null() {
                        return Ok(SqlValue::Null);
                    } else {
                        return Err(crate::error::DbError::TypeConversionError(format!(
                            "Blob 字段期望字符串,实得 {value}"
                        )));
                    }
                }
                FieldType::Text => {
                    if let Some(s) = value.as_str() {
                        return Ok(SqlValue::String(s.to_string()));
                    } else if value.is_null() {
                        return Ok(SqlValue::Null);
                    } else {
                        return Err(crate::error::DbError::TypeConversionError(format!(
                            "Text 字段期望字符串,实得 {value}"
                        )));
                    }
                }
                FieldType::Standard => {}
            }
        }

        match value {
            Value::Null => Ok(SqlValue::Null),
            Value::Bool(b) => Ok(SqlValue::Bool(*b)),
            Value::Number(n) => {
                if let Some(i) = n.as_i64() {
                    Ok(SqlValue::Int(i))
                } else if let Some(f) = n.as_f64() {
                    Ok(SqlValue::Float(f))
                } else {
                    Err(crate::error::DbError::TypeConversionError(
                        "无法转换数字类型".to_string(),
                    ))
                }
            }
            Value::String(s) => Ok(SqlValue::String(s.clone())),
            Value::Array(_) | Value::Object(_) => Ok(SqlValue::Json(value.clone())),
        }
    }
}

/// 将 `(字段, 操作符, 值)` 映射为 6 个比较类 `Condition` 变体的共享助手。
///
/// 仅处理比较操作符(`=`、`!=`、`>`、`<`、`>=`、`<=`)。无法匹配时把 `value`
/// 原样通过 `Err` 交还调用方,便于上层继续处理 like 等其它操作符而不丢失所有权。
#[derive(Debug, Clone, Copy)]
enum UnionOperator {
    Distinct,
    All,
}

#[derive(Debug, Clone, Copy)]
pub(crate) enum ArithmeticOperator {
    Add,
    Subtract,
}

impl ArithmeticOperator {
    const fn as_sql(self) -> &'static str {
        match self {
            Self::Add => "+",
            Self::Subtract => "-",
        }
    }
}

/// 查询构建器(PostgreSQL)
enum QueryExecutor<'a> {
    Pool(&'a PgPool),
    Transaction(&'a mut crate::postgres::Transaction),
}

pub struct QueryBuilder<'a> {
    executor: QueryExecutor<'a>,
    table: String,
    fields: Vec<String>,
    conditions: Vec<Condition>,
    joins: Vec<JoinClause>,
    order_by: Vec<OrderClause>,
    group_by: Vec<String>,
    having_clause: Vec<Condition>,
    limit: Option<u64>,
    offset: Option<u64>,
    distinct: bool,
    unions: Vec<(UnionOperator, Box<QueryBuilder<'a>>)>,
    field_types: HashMap<String, FieldType>,
    /// UPSERT 的冲突目标列(PostgreSQL `ON CONFLICT (...)` 必需)。
    /// 默认 `["id"]`,可通过 [`QueryBuilder::on_conflict`] 覆盖。
    conflict_columns: Vec<String>,
    /// `insert` 的 `RETURNING` 列,用于取回自增主键。默认 `"id"`。
    returning: String,
    enable_logging: bool,
}

impl<'a> QueryBuilder<'a> {
    /// 创建新的查询构建器
    pub(crate) fn new(pool: &'a PgPool, table_name: &str, enable_logging: bool) -> Self {
        Self {
            executor: QueryExecutor::Pool(pool),
            table: table_name.to_string(),
            fields: Vec::new(),
            conditions: Vec::new(),
            joins: Vec::new(),
            order_by: Vec::new(),
            group_by: Vec::new(),
            having_clause: Vec::new(),
            limit: None,
            offset: None,
            distinct: false,
            unions: Vec::new(),
            field_types: HashMap::new(),
            conflict_columns: vec!["id".to_string()],
            returning: "id".to_string(),
            enable_logging,
        }
    }

    pub(crate) fn new_transaction(
        transaction: &'a mut crate::postgres::Transaction,
        table_name: &str,
        enable_logging: bool,
    ) -> Self {
        Self {
            executor: QueryExecutor::Transaction(transaction),
            table: table_name.to_string(),
            fields: Vec::new(),
            conditions: Vec::new(),
            joins: Vec::new(),
            order_by: Vec::new(),
            group_by: Vec::new(),
            having_clause: Vec::new(),
            limit: None,
            offset: None,
            distinct: false,
            unions: Vec::new(),
            field_types: HashMap::new(),
            conflict_columns: vec!["id".to_string()],
            returning: "id".to_string(),
            enable_logging,
        }
    }

    /// 选择可信 SQL 表达式。
    ///
    /// 本方法不校验输入;外部列名请使用 [`Self::field_identifier`]。
    pub fn field(mut self, field: &crate::FieldRef) -> Self {
        self.fields.push(field.postgres_quoted().to_string());
        self
    }

    /// 添加受控聚合表达式。
    pub fn expr(mut self, expression: crate::SelectExpr) -> Self {
        self.fields.push(expression.postgres_sql());
        self
    }

    /// 选择多个可信 SQL 表达式;外部列名请使用 [`Self::field_identifiers`]。
    pub fn fields(mut self, fields: &[&crate::FieldRef]) -> Self {
        for field in fields {
            self.fields.push(field.postgres_quoted().to_string());
        }
        self
    }

    /// 标记字段为 JSON 类型
    pub fn json(mut self, field: &crate::FieldRef) -> Self {
        self.field_types
            .insert(field.as_str().to_string(), FieldType::Json);
        self
    }

    /// 标记字段为 DATETIME 类型
    pub fn datetime(mut self, field: &crate::FieldRef) -> Self {
        self.field_types
            .insert(field.as_str().to_string(), FieldType::DateTime);
        self
    }

    /// 标记字段为 TIMESTAMP 类型
    pub fn timestamp(mut self, field: &crate::FieldRef) -> Self {
        self.field_types
            .insert(field.as_str().to_string(), FieldType::Timestamp);
        self
    }

    /// 标记字段为 DECIMAL 类型
    pub fn decimal(mut self, field: &crate::FieldRef) -> Self {
        self.field_types
            .insert(field.as_str().to_string(), FieldType::Decimal);
        self
    }

    /// 标记字段为 BLOB(BYTEA)类型
    pub fn blob(mut self, field: &crate::FieldRef) -> Self {
        self.field_types
            .insert(field.as_str().to_string(), FieldType::Blob);
        self
    }

    /// 标记字段为 TEXT 类型
    pub fn text(mut self, field: &crate::FieldRef) -> Self {
        self.field_types
            .insert(field.as_str().to_string(), FieldType::Text);
        self
    }

    /// 去重
    pub fn distinct(mut self) -> Self {
        self.distinct = true;
        self
    }

    /// 使用 UNION 组合一个显式投影且输出列数相同的查询。
    pub fn union(self, other: QueryBuilder<'a>) -> Result<Self, crate::error::DbError> {
        self.add_union(other, UnionOperator::Distinct)
    }

    /// 使用 UNION ALL 组合一个显式投影且输出列数相同的查询。
    pub fn union_all(self, other: QueryBuilder<'a>) -> Result<Self, crate::error::DbError> {
        self.add_union(other, UnionOperator::All)
    }

    fn add_union(
        mut self,
        other: QueryBuilder<'a>,
        operator: UnionOperator,
    ) -> Result<Self, crate::error::DbError> {
        if self.fields.is_empty() || other.fields.is_empty() {
            return Err(crate::error::DbError::InvalidArgument(
                "UNION 各分支必须显式声明输出字段,不能使用未知列数的 *".to_string(),
            ));
        }
        if self.fields.len() != other.fields.len() {
            return Err(crate::error::DbError::InvalidArgument(format!(
                "UNION 输出列数不一致:左侧 {} 列,右侧 {} 列",
                self.fields.len(),
                other.fields.len()
            )));
        }
        self.unions.push((operator, Box::new(other)));
        Ok(self)
    }

    /// 设置 UPSERT 的冲突目标列(PostgreSQL `ON CONFLICT (...)`)
    ///
    /// 默认冲突列为 `["id"]`。当唯一约束建立在其它列(如 `email`)上时,
    /// 调用本方法覆盖,例如 `.on_conflict(&[yang_db::field!("email")])`。
    pub fn on_conflict(mut self, columns: &[&crate::FieldRef]) -> Self {
        self.conflict_columns = columns
            .iter()
            .map(|column| column.as_str().to_string())
            .collect();
        self
    }

    /// 设置 `insert` 的 `RETURNING` 列(默认 `"id"`)
    ///
    /// PostgreSQL 无 `last_insert_id()`,`insert` 通过 `RETURNING <col>` 取回主键。
    /// 当自增主键列名不是 `id` 时,用本方法指定。
    pub fn returning(mut self, column: &crate::FieldRef) -> Self {
        self.returning = column.as_str().to_string();
        self
    }

    /// 添加 AND 条件
    ///
    /// 比较操作符由封闭的 [`CompareOp`](crate::CompareOp) 表达。LIKE 仅接受字符串模式,
    /// 其它类型返回 `Err(DbError::UnsupportedOperator)`。
    pub fn where_and<V>(
        mut self,
        field: &crate::FieldRef,
        op: crate::CompareOp,
        value: V,
    ) -> Result<Self, crate::error::DbError>
    where
        V: Into<SqlValue>,
    {
        let field = field.as_str().to_string();
        let value = value.into();
        let condition = match op {
            crate::CompareOp::Eq => Condition::Eq(field, value),
            crate::CompareOp::Ne => Condition::Ne(field, value),
            crate::CompareOp::Gt => Condition::Gt(field, value),
            crate::CompareOp::Lt => Condition::Lt(field, value),
            crate::CompareOp::Gte => Condition::Gte(field, value),
            crate::CompareOp::Lte => Condition::Lte(field, value),
            crate::CompareOp::Like => match value {
                SqlValue::String(value) => Condition::Like(field, value),
                _ => {
                    return Err(crate::error::DbError::UnsupportedOperator(
                        "LIKE 仅支持字符串模式值".to_string(),
                    ))
                }
            },
        };
        self.conditions.push(condition);
        Ok(self)
    }

    /// 添加 OR 条件
    ///
    /// 遇到不支持的操作符或 LIKE 收到非字符串模式时返回 `Err(DbError::UnsupportedOperator)`。
    pub fn where_or<V>(
        mut self,
        field: &crate::FieldRef,
        op: crate::CompareOp,
        value: V,
    ) -> Result<Self, crate::error::DbError>
    where
        V: Into<SqlValue>,
    {
        let field = field.as_str().to_string();
        let value = value.into();
        let condition = match op {
            crate::CompareOp::Eq => Condition::Eq(field, value),
            crate::CompareOp::Ne => Condition::Ne(field, value),
            crate::CompareOp::Gt => Condition::Gt(field, value),
            crate::CompareOp::Lt => Condition::Lt(field, value),
            crate::CompareOp::Gte => Condition::Gte(field, value),
            crate::CompareOp::Lte => Condition::Lte(field, value),
            crate::CompareOp::Like => match value {
                SqlValue::String(value) => Condition::Like(field, value),
                _ => {
                    return Err(crate::error::DbError::UnsupportedOperator(
                        "LIKE 仅支持字符串模式值".to_string(),
                    ))
                }
            },
        };

        if !self.conditions.is_empty() {
            let mut existing = std::mem::take(&mut self.conditions);
            self.conditions.push(Condition::Or(vec![
                if existing.len() == 1 {
                    existing.remove(0)
                } else {
                    Condition::And(existing)
                },
                condition,
            ]));
        } else {
            self.conditions.push(condition);
        }

        Ok(self)
    }

    /// 添加 IN 条件
    pub fn where_in<V>(mut self, field: &crate::FieldRef, values: Vec<V>) -> Self
    where
        V: Into<SqlValue>,
    {
        let sql_values: Vec<_> = values.into_iter().map(|v| v.into()).collect();
        self.conditions
            .push(Condition::In(field.as_str().to_string(), sql_values));
        self
    }

    /// 添加受控 EXISTS 子查询。
    pub fn where_exists(mut self, subquery: crate::postgres::Subquery) -> Self {
        self.conditions.push(Condition::Exists(Box::new(subquery)));
        self
    }

    /// 添加受控 NOT EXISTS 子查询。
    pub fn where_not_exists(mut self, subquery: crate::postgres::Subquery) -> Self {
        self.conditions
            .push(Condition::NotExists(Box::new(subquery)));
        self
    }

    /// 添加受控 IN 子查询,外层字段必须是合法的单段或两段标识符。
    pub fn where_in_subquery(
        mut self,
        field: &crate::FieldRef,
        subquery: crate::postgres::Subquery,
    ) -> Self {
        self.conditions.push(Condition::InSubquery(
            field.as_str().to_string(),
            Box::new(subquery),
        ));
        self
    }

    /// 添加 BETWEEN 条件
    pub fn where_between<V>(mut self, field: &crate::FieldRef, start: V, end: V) -> Self
    where
        V: Into<SqlValue>,
    {
        self.conditions.push(Condition::Between(
            field.as_str().to_string(),
            start.into(),
            end.into(),
        ));
        self
    }

    /// 添加 IS NULL 条件
    pub fn where_null(mut self, field: &crate::FieldRef) -> Self {
        self.conditions
            .push(Condition::IsNull(field.as_str().to_string()));
        self
    }

    /// 添加 IS NOT NULL 条件
    pub fn where_not_null(mut self, field: &crate::FieldRef) -> Self {
        self.conditions
            .push(Condition::IsNotNull(field.as_str().to_string()));
        self
    }

    /// 应用由上层权限模块编译的受控布尔查询树。
    pub fn where_predicate(
        mut self,
        predicate: &crate::Predicate,
    ) -> Result<Self, crate::error::DbError> {
        self.conditions.push(predicate_condition(predicate)?);
        Ok(self)
    }

    /// 添加 HAVING 条件(仅支持 6 个比较操作符)
    pub fn having_cond<V>(
        mut self,
        field: &crate::FieldRef,
        op: crate::CompareOp,
        value: V,
    ) -> Result<Self, crate::error::DbError>
    where
        V: Into<SqlValue>,
    {
        let field = field.as_str().to_string();
        let value = value.into();
        let condition = match op {
            crate::CompareOp::Eq => Condition::Eq(field, value),
            crate::CompareOp::Ne => Condition::Ne(field, value),
            crate::CompareOp::Gt => Condition::Gt(field, value),
            crate::CompareOp::Lt => Condition::Lt(field, value),
            crate::CompareOp::Gte => Condition::Gte(field, value),
            crate::CompareOp::Lte => Condition::Lte(field, value),
            crate::CompareOp::Like => match value {
                SqlValue::String(value) => Condition::Like(field, value),
                _ => {
                    return Err(crate::error::DbError::UnsupportedOperator(
                        "LIKE 仅支持字符串模式值".to_string(),
                    ))
                }
            },
        };
        self.having_clause.push(condition);
        Ok(self)
    }

    /// 使用可信表/ON 表达式的 INNER JOIN。
    ///
    /// 外部表名/列名请先用 [`crate::postgres::identifier::quote_identifier`] /
    /// [`crate::postgres::identifier::quote_qualified`] 校验后再拼入表达式。
    pub fn join(
        mut self,
        table: &crate::TableRef,
        left: &crate::FieldRef,
        right: &crate::FieldRef,
    ) -> Self {
        use crate::postgres::field::JoinType;
        self.joins.push(JoinClause {
            join_type: JoinType::Inner,
            table: table.as_str().to_string(),
            on: format!("{} = {}", left.postgres_quoted(), right.postgres_quoted()),
        });
        self
    }

    /// LEFT JOIN
    pub fn left_join(
        mut self,
        table: &crate::TableRef,
        left: &crate::FieldRef,
        right: &crate::FieldRef,
    ) -> Self {
        use crate::postgres::field::JoinType;
        self.joins.push(JoinClause {
            join_type: JoinType::Left,
            table: table.as_str().to_string(),
            on: format!("{} = {}", left.postgres_quoted(), right.postgres_quoted()),
        });
        self
    }

    /// RIGHT JOIN
    pub fn right_join(
        mut self,
        table: &crate::TableRef,
        left: &crate::FieldRef,
        right: &crate::FieldRef,
    ) -> Self {
        use crate::postgres::field::JoinType;
        self.joins.push(JoinClause {
            join_type: JoinType::Right,
            table: table.as_str().to_string(),
            on: format!("{} = {}", left.postgres_quoted(), right.postgres_quoted()),
        });
        self
    }

    /// 按可信 SQL 表达式排序;外部列名请先用 [`crate::postgres::identifier::quote_identifier`]
    /// 校验后再拼入表达式。
    pub fn order(mut self, field: &crate::FieldRef, order: crate::SortOrder) -> Self {
        self.order_by.push(OrderClause {
            field: field.postgres_quoted().to_string(),
            asc: order.is_ascending(),
        });
        self
    }

    /// 按可信 SQL 表达式分组;外部列名请先用 [`crate::postgres::identifier::quote_identifier`]
    /// 校验后再拼入表达式。
    pub fn group(mut self, field: &crate::FieldRef) -> Self {
        self.group_by.push(field.postgres_quoted().to_string());
        self
    }

    /// 限制返回数量
    pub fn limit(mut self, limit: u64) -> Self {
        self.limit = Some(limit);
        self
    }

    /// 偏移量
    pub fn offset(mut self, offset: u64) -> Self {
        self.offset = Some(offset);
        self
    }

    /// 尝试获取生成的 SQL(用于调试)。
    ///
    /// 与 [`Self::to_sql`] 不同,本方法不会吞掉 SQL 生成错误。调用方需要区分非法表名、
    /// 缺少 `GROUP BY` 等生产级配置错误时,应优先使用本方法。
    pub fn try_to_sql(&self) -> Result<String, crate::error::DbError> {
        let mut generator = SqlGenerator::new();
        generator.build_select(self)?;
        Ok(generator.get_sql().to_string())
    }

    pub(crate) fn render_for_transaction(
        &self,
        lock: Option<crate::RowLock>,
    ) -> Result<(String, Vec<SqlValue>), crate::error::DbError> {
        if lock.is_some()
            && (self.distinct
                || !self.group_by.is_empty()
                || !self.having_clause.is_empty()
                || !self.unions.is_empty())
        {
            return Err(crate::error::DbError::InvalidArgument(
                "行锁不支持 DISTINCT、GROUP BY、HAVING 或 UNION 查询".to_string(),
            ));
        }
        let mut generator = SqlGenerator::new();
        generator.build_select(self)?;
        if let Some(lock) = lock {
            generator.sql.push(' ');
            generator.sql.push_str(lock.as_sql());
        }
        Ok((generator.sql, generator.params))
    }

    /// 获取生成的 SQL(用于调试)
    ///
    /// 兼容历史 `String` 返回值;生成失败时返回固定的不可执行哨兵,避免旧降级逻辑把
    /// 未校验表名或不完整查询拼成看似可执行的 SQL。需要错误细节请使用 [`Self::try_to_sql`]。
    pub fn to_sql(&self) -> String {
        match self.try_to_sql() {
            Ok(sql) => sql,
            Err(err) => {
                if self.enable_logging {
                    log::warn!("生成 SELECT SQL 失败: {err}");
                }
                "/* SQL generation failed */".to_string()
            }
        }
    }

    /// 查询单条记录(自动追加 LIMIT 1)
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "postgresql", db.operation = "select", db.collection = %self.table, otel.kind = "client")
    )]
    pub async fn find<T>(mut self) -> Result<Option<T>, crate::error::DbError>
    where
        T: for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow> + Send + Unpin,
    {
        self.limit = Some(1);

        let mut generator = SqlGenerator::new();
        generator.build_select(&self)?;
        let sql = generator.get_sql();
        let params = generator.get_params();

        if self.enable_logging {
            log::debug!("执行 find() 查询: {}", sql);
            log::debug!("参数: {:?}", params);
        }

        let mut query = sqlx::query_as::<_, T>(sql);
        for param in params {
            query = bind_param(query, param);
        }

        let result = match self.executor {
            QueryExecutor::Pool(pool) => query.fetch_optional(pool).await,
            QueryExecutor::Transaction(transaction) => {
                let connection = transaction.executor().ok_or_else(|| {
                    crate::error::DbError::TransactionError("事务已提交或回滚".to_string())
                })?;
                query.fetch_optional(&mut *connection).await
            }
        };
        match result {
            Ok(row) => Ok(row),
            Err(e) => {
                log::error!("find() 查询失败: {}", e);
                Err(crate::error::DbError::from(e))
            }
        }
    }

    /// 查询多条记录
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "postgresql", db.operation = "select", db.collection = %self.table, otel.kind = "client")
    )]
    pub async fn select<T>(self) -> Result<Vec<T>, crate::error::DbError>
    where
        T: for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow> + Send + Unpin,
    {
        let mut generator = SqlGenerator::new();
        generator.build_select(&self)?;
        let sql = generator.get_sql();
        let params = generator.get_params();

        if self.enable_logging {
            log::debug!("执行 select() 查询: {}", sql);
            log::debug!("参数: {:?}", params);
        }

        let mut query = sqlx::query_as::<_, T>(sql);
        for param in params {
            query = bind_param(query, param);
        }

        let result = match self.executor {
            QueryExecutor::Pool(pool) => query.fetch_all(pool).await,
            QueryExecutor::Transaction(transaction) => {
                let connection = transaction.executor().ok_or_else(|| {
                    crate::error::DbError::TransactionError("事务已提交或回滚".to_string())
                })?;
                query.fetch_all(&mut *connection).await
            }
        };
        match result {
            Ok(rows) => Ok(rows),
            Err(e) => {
                log::error!("select() 查询失败: {}", e);
                Err(crate::error::DbError::from(e))
            }
        }
    }

    /// 标量查询助手(内部):只选 `select_expr`、加 LIMIT 1、执行单行单值查询。
    async fn fetch_scalar<C>(
        mut self,
        select_expr: &str,
    ) -> Result<Option<C>, crate::error::DbError>
    where
        C: for<'r> sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type<sqlx::Postgres> + Send + Unpin,
    {
        self.fields.clear();
        self.fields.push(select_expr.to_string());
        self.limit = Some(1);

        let mut generator = SqlGenerator::new();
        generator.build_select(&self)?;
        let sql = generator.get_sql();
        let params = generator.get_params();

        if self.enable_logging {
            log::debug!("执行标量查询: {}", sql);
            log::debug!("参数: {:?}", params);
        }

        let mut query = sqlx::query_scalar::<_, C>(sql);
        for param in params {
            query = bind_scalar_param(query, param);
        }

        let result = match self.executor {
            QueryExecutor::Pool(pool) => query.fetch_optional(pool).await,
            QueryExecutor::Transaction(transaction) => {
                let connection = transaction.executor().ok_or_else(|| {
                    crate::error::DbError::TransactionError("事务已提交或回滚".to_string())
                })?;
                query.fetch_optional(&mut *connection).await
            }
        };
        match result {
            Ok(value) => Ok(value),
            Err(e) => {
                log::error!("标量查询失败: {}", e);
                Err(crate::error::DbError::from(e))
            }
        }
    }

    /// 查询单个字段值(自动追加 LIMIT 1)
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "postgresql", db.operation = "select", db.collection = %self.table, otel.kind = "client")
    )]
    pub async fn value<T>(self, field: &crate::FieldRef) -> Result<Option<T>, crate::error::DbError>
    where
        T: for<'r> sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type<sqlx::Postgres> + Send + Unpin,
    {
        if self.enable_logging {
            log::debug!("执行 value() 查询,字段: {}", field.as_str());
        }
        let field = super::identifier::quote_identifier(field.as_str())?;
        self.fetch_scalar::<T>(&field).await
    }

    /// 统计记录数量(COUNT(*))
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "postgresql", db.operation = "select", db.collection = %self.table, otel.kind = "client")
    )]
    pub async fn count(self) -> Result<i64, crate::error::DbError> {
        if self.enable_logging {
            log::debug!("执行 count() 查询");
        }
        let result = self.fetch_scalar::<i64>("COUNT(*)").await?;
        Ok(result.unwrap_or(0))
    }
    /// 计算字段总和(SUM)
    ///
    /// 使用 `CAST(SUM(field) AS DOUBLE PRECISION)` 统一返回 `f64`,
    /// 与 MySQL 后端的 `AS DOUBLE` 对应(PostgreSQL 的等价类型为 `DOUBLE PRECISION`)。
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "postgresql", db.operation = "select", db.collection = %self.table, otel.kind = "client")
    )]
    pub async fn sum(self, field: &crate::FieldRef) -> Result<Option<f64>, crate::error::DbError> {
        if self.enable_logging {
            log::debug!("执行 sum() 查询,字段: {}", field.as_str());
        }
        // 验证需求: ID-1 — 聚合方法对标识符做转义,杜绝注入
        let quoted_field = super::identifier::quote_identifier(field.as_str())?;
        let sum_expr = format!("CAST(SUM({quoted_field}) AS DOUBLE PRECISION)");
        self.fetch_scalar::<Option<f64>>(&sum_expr)
            .await
            .map(Option::flatten)
    }

    /// 计算字段平均值(AVG)
    ///
    /// 使用 `CAST(AVG(field) AS DOUBLE PRECISION)` 统一返回 `f64`。
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "postgresql", db.operation = "select", db.collection = %self.table, otel.kind = "client")
    )]
    pub async fn avg(self, field: &crate::FieldRef) -> Result<Option<f64>, crate::error::DbError> {
        if self.enable_logging {
            log::debug!("执行 avg() 查询,字段: {}", field.as_str());
        }
        // 验证需求: ID-1 — 聚合方法对标识符做转义,杜绝注入
        let quoted_field = super::identifier::quote_identifier(field.as_str())?;
        let avg_expr = format!("CAST(AVG({quoted_field}) AS DOUBLE PRECISION)");
        self.fetch_scalar::<Option<f64>>(&avg_expr)
            .await
            .map(Option::flatten)
    }

    /// 获取字段最小值(MIN)
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "postgresql", db.operation = "select", db.collection = %self.table, otel.kind = "client")
    )]
    pub async fn min<T>(self, field: &crate::FieldRef) -> Result<Option<T>, crate::error::DbError>
    where
        T: for<'r> sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type<sqlx::Postgres> + Send + Unpin,
    {
        if self.enable_logging {
            log::debug!("执行 min() 查询,字段: {}", field.as_str());
        }
        // 验证需求: ID-1 — 聚合方法对标识符做转义,杜绝注入
        let quoted_field = super::identifier::quote_identifier(field.as_str())?;
        let min_expr = format!("MIN({quoted_field})");
        self.fetch_scalar::<Option<T>>(&min_expr)
            .await
            .map(Option::flatten)
    }

    /// 获取字段最大值(MAX)
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "postgresql", db.operation = "select", db.collection = %self.table, otel.kind = "client")
    )]
    pub async fn max<T>(self, field: &crate::FieldRef) -> Result<Option<T>, crate::error::DbError>
    where
        T: for<'r> sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type<sqlx::Postgres> + Send + Unpin,
    {
        if self.enable_logging {
            log::debug!("执行 max() 查询,字段: {}", field.as_str());
        }
        // 验证需求: ID-1 — 聚合方法对标识符做转义,杜绝注入
        let quoted_field = super::identifier::quote_identifier(field.as_str())?;
        let max_expr = format!("MAX({quoted_field})");
        self.fetch_scalar::<Option<T>>(&max_expr)
            .await
            .map(Option::flatten)
    }
    /// 插入数据
    ///
    /// 执行 INSERT 操作并通过 `RETURNING <col>` 取回自增主键(PostgreSQL 无
    /// `last_insert_id()`)。`<col>` 默认 `"id"`,可用 [`QueryBuilder::returning`] 覆盖。
    ///
    /// # 返回
    /// - Ok(u64): 插入成功,返回 `RETURNING` 列的值(自增主键)
    /// - Err(DbError): 插入失败
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "postgresql", db.operation = "insert", db.collection = %self.table, otel.kind = "client")
    )]
    pub async fn insert<T>(self, data: &T) -> Result<u64, crate::error::DbError>
    where
        T: serde::Serialize,
    {
        if self.enable_logging {
            log::debug!("执行 insert() 操作,表: {}", self.table);
        }

        let json_data = serde_json::to_value(data).map_err(|e| {
            crate::error::DbError::SerializationError(format!("数据序列化失败: {}", e))
        })?;

        let mut generator = SqlGenerator::new();
        generator.build_insert(&self.table, &json_data, &self.field_types)?;

        // PostgreSQL 无 last_insert_id(),改用 RETURNING 取回自增主键。
        // 用 CAST(... AS BIGINT) 统一首列类型:SERIAL 为 INT4、BIGSERIAL 为 INT8,
        // sqlx 解码严格匹配类型,强制转为 BIGINT 后即可统一按 i64 解码。
        let returning_quoted = super::identifier::quote_identifier(&self.returning)?;
        let sql = format!(
            "{} RETURNING CAST({} AS BIGINT)",
            generator.get_sql(),
            returning_quoted
        );
        let params = generator.get_params();

        if self.enable_logging {
            log::debug!("执行 insert() SQL: {}", sql);
            log::debug!("参数: {:?}", params);
        }

        // RETURNING 首列解码为 i64,再转回 u64 保持与 MySQL 后端一致的返回类型
        let mut query = sqlx::query_scalar::<_, i64>(&sql);
        for param in params {
            query = bind_scalar_param(query, param);
        }

        let result = match self.executor {
            QueryExecutor::Pool(pool) => query.fetch_one(pool).await,
            QueryExecutor::Transaction(transaction) => {
                let connection = transaction.executor().ok_or_else(|| {
                    crate::error::DbError::TransactionError("事务已提交或回滚".to_string())
                })?;
                query.fetch_one(&mut *connection).await
            }
        };
        match result {
            Ok(id) => {
                if self.enable_logging {
                    log::debug!("insert() 成功,插入 ID: {}", id);
                }
                u64::try_from(id)
                    .map_err(|_| crate::error::DbError::InvalidArgument("返回主键为负".into()))
            }
            Err(e) => {
                log::error!("insert() 失败: {}", e);
                Err(crate::error::DbError::from(e))
            }
        }
    }
    /// 批量插入数据
    ///
    /// 使用默认批大小 [`INSERT_BATCH_SIZE`](500)分批执行,返回总受影响行数。
    /// 批量插入不使用 `RETURNING`,仅返回 `rows_affected()`。
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "postgresql", db.operation = "insert", db.collection = %self.table, otel.kind = "client")
    )]
    pub async fn insert_batch<T>(self, data: &[T]) -> Result<u64, crate::error::DbError>
    where
        T: serde::Serialize,
    {
        self.insert_batch_with_size(data, INSERT_BATCH_SIZE).await
    }

    /// 批量插入数据(自定义批次大小)
    ///
    /// 允许调用方根据网络延迟、数据大小等自定义每批最大记录数(必须 > 0)。
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "postgresql", db.operation = "insert", db.collection = %self.table, otel.kind = "client")
    )]
    pub async fn insert_batch_with_size<T>(
        self,
        data: &[T],
        batch_size: usize,
    ) -> Result<u64, crate::error::DbError>
    where
        T: serde::Serialize,
    {
        if batch_size == 0 {
            return Err(crate::error::DbError::SerializationError(
                "batch_size 不能为 0".to_string(),
            ));
        }

        if self.enable_logging {
            log::debug!(
                "执行 insert_batch_with_size() 操作,表: {},记录数: {},批次大小: {}",
                self.table,
                data.len(),
                batch_size
            );
        }

        if data.is_empty() {
            return Err(crate::error::DbError::SerializationError(
                "批量插入数据不能为空".to_string(),
            ));
        }

        // 单批次走 pool 免事务;多批次单事务包裹整体回滚(DB-4,比照 update_batch)。
        let chunks: Vec<&[T]> = data.chunks(batch_size).collect();
        if chunks.len() == 1 {
            let enable_logging = self.enable_logging;
            let affected = self.insert_chunk(chunks[0]).await?;
            if enable_logging {
                log::debug!("insert_batch_with_size() 单批完成,影响 {} 行", affected);
            }
            return Ok(affected);
        }

        let mut total_affected = 0u64;
        match self.executor {
            QueryExecutor::Pool(pool) => {
                let mut transaction = pool.begin().await.map_err(crate::error::DbError::from)?;
                for (batch_index, chunk) in chunks.iter().enumerate() {
                    let result = execute_insert_chunk(
                        &mut transaction,
                        &self.table,
                        chunk,
                        &self.field_types,
                    )
                    .await?;
                    total_affected += result;
                    if self.enable_logging {
                        log::debug!("第 {} 批插入成功,影响 {} 行", batch_index + 1, result);
                    }
                }
                transaction
                    .commit()
                    .await
                    .map_err(crate::error::DbError::from)?;
            }
            QueryExecutor::Transaction(transaction) => {
                let connection = transaction.executor().ok_or_else(|| {
                    crate::error::DbError::TransactionError("事务已提交或回滚".to_string())
                })?;
                for (batch_index, chunk) in chunks.iter().enumerate() {
                    let result = execute_insert_chunk(
                        &mut *connection,
                        &self.table,
                        chunk,
                        &self.field_types,
                    )
                    .await?;
                    total_affected += result;
                    if self.enable_logging {
                        log::debug!("第 {} 批插入成功,影响 {} 行", batch_index + 1, result);
                    }
                }
            }
        }

        if self.enable_logging {
            log::debug!(
                "insert_batch_with_size() 多批事务提交完成,总共影响 {} 行",
                total_affected
            );
        }

        Ok(total_affected)
    }
    /// 插入单个批次的数据(内部方法)
    ///
    async fn insert_chunk<T>(self, data: &[T]) -> Result<u64, crate::error::DbError>
    where
        T: serde::Serialize,
    {
        let json_data_list: Result<Vec<_>, _> = data
            .iter()
            .map(|item| {
                serde_json::to_value(item).map_err(|e| {
                    crate::error::DbError::SerializationError(format!("数据序列化失败: {}", e))
                })
            })
            .collect();

        let json_data_list = json_data_list?;

        let mut generator = SqlGenerator::new();
        generator.build_insert_batch(&self.table, &json_data_list, &self.field_types)?;

        let sql = generator.get_sql();
        let params = generator.get_params();

        if self.enable_logging {
            log::debug!("执行 insert_chunk() SQL: {}", sql);
            log::debug!("参数数量: {}", params.len());
        }

        let mut query = sqlx::query(sql);
        for param in params {
            query = bind_execute_param(query, param);
        }

        let result = match self.executor {
            QueryExecutor::Pool(pool) => query.execute(pool).await,
            QueryExecutor::Transaction(transaction) => {
                let connection = transaction.executor().ok_or_else(|| {
                    crate::error::DbError::TransactionError("事务已提交或回滚".to_string())
                })?;
                query.execute(&mut *connection).await
            }
        };
        match result {
            Ok(query_result) => {
                let rows_affected = query_result.rows_affected();
                if self.enable_logging {
                    log::debug!("insert_chunk() 成功,影响 {} 行", rows_affected);
                }
                Ok(rows_affected)
            }
            Err(e) => {
                log::error!("insert_chunk() 失败: {}", e);
                Err(crate::error::DbError::from(e))
            }
        }
    }
    /// 更新数据
    ///
    /// 执行 UPDATE 操作。为防止误操作,必须提供 WHERE 条件,否则返回
    /// `MissingWhereClause`。返回受影响的行数。
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "postgresql", db.operation = "update", db.collection = %self.table, otel.kind = "client")
    )]
    pub async fn update<T>(self, data: &T) -> Result<u64, crate::error::DbError>
    where
        T: serde::Serialize,
    {
        if self.enable_logging {
            log::debug!("执行 update() 操作,表: {}", self.table);
        }

        if self.conditions.is_empty() {
            log::warn!("update() 操作缺少 WHERE 条件,禁止全表更新");
            return Err(crate::error::DbError::MissingWhereClause);
        }

        let json_data = serde_json::to_value(data).map_err(|e| {
            crate::error::DbError::SerializationError(format!("数据序列化失败: {}", e))
        })?;

        let mut generator = SqlGenerator::new();
        generator.build_update(&self.table, &json_data, &self.field_types, &self.conditions)?;

        let sql = generator.get_sql();
        let params = generator.get_params();

        if self.enable_logging {
            log::debug!("执行 update() SQL: {}", sql);
            log::debug!("参数: {:?}", params);
        }

        let mut query = sqlx::query(sql);
        for param in params {
            query = bind_execute_param(query, param);
        }

        let result = match self.executor {
            QueryExecutor::Pool(pool) => query.execute(pool).await,
            QueryExecutor::Transaction(transaction) => {
                let connection = transaction.executor().ok_or_else(|| {
                    crate::error::DbError::TransactionError("事务已提交或回滚".to_string())
                })?;
                query.execute(&mut *connection).await
            }
        };
        match result {
            Ok(query_result) => {
                let rows_affected = query_result.rows_affected();
                if self.enable_logging {
                    log::debug!("update() 成功,影响 {} 行", rows_affected);
                }
                Ok(rows_affected)
            }
            Err(e) => {
                log::error!("update() 失败: {}", e);
                Err(crate::error::DbError::from(e))
            }
        }
    }

    /// 原子增加字段值;增量使用绑定参数,且必须提供 WHERE。
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "postgresql", db.operation = "update", db.collection = %self.table, otel.kind = "client")
    )]
    pub async fn increment(
        self,
        field: &crate::FieldRef,
        amount: i64,
    ) -> Result<u64, crate::error::DbError> {
        self.execute_arithmetic_update(field, amount, ArithmeticOperator::Add)
            .await
    }

    /// 原子减少字段值;增量使用绑定参数,且必须提供 WHERE。
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "postgresql", db.operation = "update", db.collection = %self.table, otel.kind = "client")
    )]
    pub async fn decrement(
        self,
        field: &crate::FieldRef,
        amount: i64,
    ) -> Result<u64, crate::error::DbError> {
        self.execute_arithmetic_update(field, amount, ArithmeticOperator::Subtract)
            .await
    }

    async fn execute_arithmetic_update(
        self,
        field: &crate::FieldRef,
        amount: i64,
        operator: ArithmeticOperator,
    ) -> Result<u64, crate::error::DbError> {
        let mut generator = SqlGenerator::new();
        generator.build_arithmetic_update(
            &self.table,
            field.as_str(),
            operator,
            amount,
            &self.conditions,
        )?;
        let mut query = sqlx::query(generator.get_sql());
        for param in generator.get_params() {
            query = bind_execute_param(query, param);
        }
        let result = match self.executor {
            QueryExecutor::Pool(pool) => query.execute(pool).await,
            QueryExecutor::Transaction(transaction) => {
                let connection = transaction.executor().ok_or_else(|| {
                    crate::error::DbError::TransactionError("事务已提交或回滚".to_string())
                })?;
                query.execute(&mut *connection).await
            }
        }?;
        Ok(result.rows_affected())
    }

    /// 删除数据
    ///
    /// 执行 DELETE 操作。为防止误操作,必须提供 WHERE 条件,否则返回
    /// `MissingWhereClause`。返回受影响的行数。
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "postgresql", db.operation = "delete", db.collection = %self.table, otel.kind = "client")
    )]
    pub async fn delete(self) -> Result<u64, crate::error::DbError> {
        if self.enable_logging {
            log::debug!("执行 delete() 操作,表: {}", self.table);
        }

        if self.conditions.is_empty() {
            log::warn!("delete() 操作缺少 WHERE 条件,禁止全表删除");
            return Err(crate::error::DbError::MissingWhereClause);
        }

        let mut generator = SqlGenerator::new();
        generator.build_delete(&self.table, &self.conditions)?;

        let sql = generator.get_sql();
        let params = generator.get_params();

        if self.enable_logging {
            log::debug!("执行 delete() SQL: {}", sql);
            log::debug!("参数: {:?}", params);
        }

        let mut query = sqlx::query(sql);
        for param in params {
            query = bind_execute_param(query, param);
        }

        let result = match self.executor {
            QueryExecutor::Pool(pool) => query.execute(pool).await,
            QueryExecutor::Transaction(transaction) => {
                let connection = transaction.executor().ok_or_else(|| {
                    crate::error::DbError::TransactionError("事务已提交或回滚".to_string())
                })?;
                query.execute(&mut *connection).await
            }
        };
        match result {
            Ok(query_result) => {
                let rows_affected = query_result.rows_affected();
                if self.enable_logging {
                    log::debug!("delete() 成功,影响 {} 行", rows_affected);
                }
                Ok(rows_affected)
            }
            Err(e) => {
                log::error!("delete() 失败: {}", e);
                Err(crate::error::DbError::from(e))
            }
        }
    }
    /// 批量更新记录
    ///
    /// 使用 CASE WHEN 策略在单次查询中更新多条记录,自动分批(每批
    /// [`UPDATE_BATCH_SIZE`],1000;宽表按列数自动缩小),所有批次在同一事务中
    /// 执行保证原子性。返回总受影响行数。
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "postgresql", db.operation = "update", db.collection = %self.table, otel.kind = "client")
    )]
    pub async fn update_batch<T>(
        self,
        records: &[T],
        where_field: &crate::FieldRef,
    ) -> Result<u64, crate::error::DbError>
    where
        T: serde::Serialize,
    {
        self.update_batch_with_size(records, where_field, UPDATE_BATCH_SIZE)
            .await
    }

    /// 批量更新记录(自定义批次大小)
    ///
    /// 与 [`QueryBuilder::update_batch`] 相同,但允许调用方自定义每批最大记录数;
    /// 宽表会自动按列数缩小批大小,避免超出协议占位符上限。
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "postgresql", db.operation = "update", db.collection = %self.table, otel.kind = "client")
    )]
    pub async fn update_batch_with_size<T>(
        self,
        records: &[T],
        where_field: &crate::FieldRef,
        batch_size: usize,
    ) -> Result<u64, crate::error::DbError>
    where
        T: serde::Serialize,
    {
        if batch_size == 0 {
            return Err(crate::error::DbError::SerializationError(
                "batch_size 不能为 0".to_string(),
            ));
        }

        if records.is_empty() {
            return Err(crate::error::DbError::SerializationError(
                "批量更新数据不能为空".to_string(),
            ));
        }

        let json_records: Vec<serde_json::Value> = records
            .iter()
            .map(|r| {
                serde_json::to_value(r).map_err(|e| {
                    crate::error::DbError::SerializationError(format!("数据序列化失败: {}", e))
                })
            })
            .collect::<Result<_, _>>()?;

        // 按「非主键列数」推导安全批大小:宽表单条占位符可能超协议上限,需按列缩小
        let field_count = update_field_count(&json_records, where_field.as_str());
        let per_record = field_count.saturating_mul(2).saturating_add(1);
        if per_record > MAX_BIND_PARAMS {
            return Err(crate::error::DbError::InvalidArgument(format!(
                "批量更新单行需要 {per_record} 个占位符,超过协议上限 {MAX_BIND_PARAMS},请减少更新列数"
            )));
        }
        let batch_size = derive_update_batch_size(field_count, batch_size);

        let mut total = 0u64;
        match self.executor {
            QueryExecutor::Pool(pool) => {
                let mut transaction = pool.begin().await.map_err(crate::error::DbError::from)?;
                for chunk in json_records.chunks(batch_size) {
                    total += execute_update_chunk(
                        &mut transaction,
                        &self.table,
                        chunk,
                        where_field,
                        &self.field_types,
                    )
                    .await?;
                }
                transaction
                    .commit()
                    .await
                    .map_err(crate::error::DbError::from)?;
            }
            QueryExecutor::Transaction(transaction) => {
                let connection = transaction.executor().ok_or_else(|| {
                    crate::error::DbError::TransactionError("事务已提交或回滚".to_string())
                })?;
                for chunk in json_records.chunks(batch_size) {
                    total += execute_update_chunk(
                        &mut *connection,
                        &self.table,
                        chunk,
                        where_field,
                        &self.field_types,
                    )
                    .await?;
                }
            }
        }
        Ok(total)
    }

    /// UPSERT - 插入或更新记录
    ///
    /// 使用 PostgreSQL `INSERT ... ON CONFLICT (...) DO UPDATE SET col = EXCLUDED.col`
    /// 语法。冲突目标列默认 `["id"]`,可用 [`QueryBuilder::on_conflict`] 覆盖。
    /// 返回 `rows_affected()`。
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "postgresql", db.operation = "upsert", db.collection = %self.table, otel.kind = "client")
    )]
    pub async fn upsert<T>(self, data: &T) -> Result<u64, crate::error::DbError>
    where
        T: serde::Serialize,
    {
        if self.enable_logging {
            log::debug!("执行 upsert() 操作,表: {}", self.table);
        }

        let json_data = serde_json::to_value(data).map_err(|e| {
            crate::error::DbError::SerializationError(format!("数据序列化失败: {}", e))
        })?;

        let mut generator = SqlGenerator::new();
        generator.build_upsert(
            &self.table,
            &json_data,
            &self.field_types,
            &self.conflict_columns,
        )?;

        let sql = generator.get_sql();
        let params = generator.get_params();

        if self.enable_logging {
            log::debug!("执行 upsert() SQL: {}", sql);
        }

        let mut query = sqlx::query(sql);
        for param in params {
            query = bind_execute_param(query, param);
        }

        let result = match self.executor {
            QueryExecutor::Pool(pool) => query.execute(pool).await,
            QueryExecutor::Transaction(transaction) => {
                let connection = transaction.executor().ok_or_else(|| {
                    crate::error::DbError::TransactionError("事务已提交或回滚".to_string())
                })?;
                query.execute(&mut *connection).await
            }
        }
        .map_err(crate::error::DbError::from)?;
        let rows = result.rows_affected();

        if self.enable_logging {
            log::debug!("upsert() 完成,rows_affected: {}", rows);
        }

        Ok(rows)
    }
}

/// 绑定参数到执行查询(用于 INSERT/UPDATE/DELETE,PostgreSQL)
///
/// 使用 `bind_value_match!` 宏统一处理 `SqlValue` 各变体的绑定逻辑,
/// 与 MySQL 后端的同名函数对齐,仅后端类型不同。
fn bind_execute_param<'q>(
    query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
    param: &SqlValue,
) -> sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments> {
    bind_value_match!(query, param)
}

/// 绑定参数到 `query_as` 查询(PostgreSQL)
///
/// 使用 `bind_value_match!` 宏统一处理 `SqlValue` 各变体的绑定逻辑,
/// 与 MySQL 后端的同名函数对齐,仅后端类型不同(`Postgres` / `PgArguments` / `PgRow`)。
pub(crate) fn bind_param<'q, T>(
    query: sqlx::query::QueryAs<'q, sqlx::Postgres, T, sqlx::postgres::PgArguments>,
    param: &SqlValue,
) -> sqlx::query::QueryAs<'q, sqlx::Postgres, T, sqlx::postgres::PgArguments>
where
    T: for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow> + Send + Unpin,
{
    bind_value_match!(query, param)
}

/// 绑定参数到标量查询(PostgreSQL)
///
/// 泛型于标量类型 `C`,供 `value::<T>()` 与 `count()`(`i64`)等复用。
fn bind_scalar_param<'q, C>(
    query: sqlx::query::QueryScalar<'q, sqlx::Postgres, C, sqlx::postgres::PgArguments>,
    param: &SqlValue,
) -> sqlx::query::QueryScalar<'q, sqlx::Postgres, C, sqlx::postgres::PgArguments>
where
    C: for<'r> sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type<sqlx::Postgres> + Send + Unpin,
{
    bind_value_match!(query, param)
}

/// 绑定参数到标量查询(Option 类型,PostgreSQL)
///
/// 聚合/标量方法现统一走 `fetch_scalar` + `bind_scalar_param`(后者对 `Option<T>`
/// 输出类型同样适用),本函数暂无调用方但保留作为公开内部表面,标注 allow(dead_code)。
#[allow(dead_code)]
fn bind_scalar_param_option<'q, T>(
    query: sqlx::query::QueryScalar<'q, sqlx::Postgres, Option<T>, sqlx::postgres::PgArguments>,
    param: &SqlValue,
) -> sqlx::query::QueryScalar<'q, sqlx::Postgres, Option<T>, sqlx::postgres::PgArguments>
where
    T: for<'r> sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type<sqlx::Postgres> + Send + Unpin,
{
    bind_value_match!(query, param)
}

async fn execute_insert_chunk<T>(
    connection: &mut sqlx::PgConnection,
    table: &str,
    data: &[T],
    field_types: &HashMap<String, FieldType>,
) -> Result<u64, crate::error::DbError>
where
    T: serde::Serialize,
{
    let json_data_list = data
        .iter()
        .map(|item| {
            serde_json::to_value(item).map_err(|error| {
                crate::error::DbError::SerializationError(format!("数据序列化失败: {error}"))
            })
        })
        .collect::<Result<Vec<_>, _>>()?;
    let mut generator = SqlGenerator::new();
    generator.build_insert_batch(table, &json_data_list, field_types)?;
    let mut query = sqlx::query(generator.get_sql());
    for param in generator.get_params() {
        query = bind_execute_param(query, param);
    }
    Ok(query.execute(connection).await?.rows_affected())
}

async fn execute_update_chunk(
    connection: &mut sqlx::PgConnection,
    table: &str,
    records: &[serde_json::Value],
    where_field: &crate::FieldRef,
    field_types: &HashMap<String, FieldType>,
) -> Result<u64, crate::error::DbError> {
    let mut generator = SqlGenerator::new();
    generator.build_update_batch(table, records, where_field.as_str(), field_types)?;
    let mut query = sqlx::query(generator.get_sql());
    for param in generator.get_params() {
        query = bind_execute_param(query, param);
    }
    Ok(query.execute(connection).await?.rows_affected())
}

fn predicate_condition(predicate: &crate::Predicate) -> Result<Condition, crate::error::DbError> {
    let condition = match predicate {
        crate::Predicate::Compare(field, operator, value) => {
            let name = field.as_str().to_string();
            if matches!(operator, crate::CompareOp::Like) {
                return value
                    .as_str()
                    .map(|pattern| Condition::Like(name, pattern.to_string()))
                    .ok_or_else(|| {
                        crate::error::DbError::InvalidArgument(
                            "LIKE predicate requires string value".to_string(),
                        )
                    });
            }
            let value = predicate_value(value);
            match operator {
                crate::CompareOp::Eq => Condition::Eq(name, value),
                crate::CompareOp::Ne => Condition::Ne(name, value),
                crate::CompareOp::Gt => Condition::Gt(name, value),
                crate::CompareOp::Lt => Condition::Lt(name, value),
                crate::CompareOp::Gte => Condition::Gte(name, value),
                crate::CompareOp::Lte => Condition::Lte(name, value),
                crate::CompareOp::Like => {
                    return Err(crate::error::DbError::InvalidArgument(
                        "LIKE predicate normalization failed".to_string(),
                    ));
                }
            }
        }
        crate::Predicate::In(field, values) => Condition::In(
            field.as_str().to_string(),
            values.iter().map(predicate_value).collect(),
        ),
        crate::Predicate::NotIn(field, values) => Condition::NotIn(
            field.as_str().to_string(),
            values.iter().map(predicate_value).collect(),
        ),
        crate::Predicate::Between(field, start, end) => Condition::Between(
            field.as_str().to_string(),
            predicate_value(start),
            predicate_value(end),
        ),
        crate::Predicate::IsNull(field) => Condition::IsNull(field.as_str().to_string()),
        crate::Predicate::IsNotNull(field) => Condition::IsNotNull(field.as_str().to_string()),
        crate::Predicate::And(values) => Condition::And(
            values
                .iter()
                .map(predicate_condition)
                .collect::<Result<Vec<_>, _>>()?,
        ),
        crate::Predicate::Or(values) => Condition::Or(
            values
                .iter()
                .map(predicate_condition)
                .collect::<Result<Vec<_>, _>>()?,
        ),
    };
    Ok(condition)
}

fn predicate_value(value: &serde_json::Value) -> SqlValue {
    match value {
        serde_json::Value::Null => SqlValue::Null,
        serde_json::Value::Bool(value) => SqlValue::Bool(*value),
        serde_json::Value::Number(value) => {
            value.as_i64().map(SqlValue::Int).unwrap_or_else(|| {
                value
                    .as_u64()
                    .map(SqlValue::from)
                    .or_else(|| value.as_f64().map(SqlValue::Float))
                    .unwrap_or_else(|| SqlValue::String(value.to_string()))
            })
        }
        serde_json::Value::String(value) => SqlValue::String(value.clone()),
        serde_json::Value::Array(_) | serde_json::Value::Object(_) => SqlValue::Json(value.clone()),
    }
}

#[cfg(test)]
mod predicate_scalar_tests {
    use super::{predicate_value, SqlValue};

    #[test]
    fn controlled_predicates_bind_json_scalars_as_sql_scalars() {
        assert!(matches!(
            predicate_value(&serde_json::json!("alice")),
            SqlValue::String(value) if value == "alice"
        ));
        assert!(matches!(
            predicate_value(&serde_json::json!(42)),
            SqlValue::Int(42)
        ));
        assert!(matches!(
            predicate_value(&serde_json::json!(true)),
            SqlValue::Bool(true)
        ));
        assert!(matches!(
            predicate_value(&serde_json::json!({"role": "admin"})),
            SqlValue::Json(_)
        ));
    }
}
// PLACEHOLDER_TESTS

#[cfg(test)]
#[allow(deprecated)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::postgres::Subquery;
    use sqlx::postgres::PgPoolOptions;

    /// 获取或创建共享懒连接池(仅验证 URL,不立即建立连接)。
    /// 用于只测试 SQL 生成逻辑、不需要真实数据库连接的单元测试。
    /// 使用 OnceLock + 静态 Tokio 运行时确保池在有效上下文中创建和驻留;
    /// `connect_lazy` 不会发起网络往返,但仍需运行时上下文。
    fn make_sync_test_pool() -> &'static PgPool {
        use std::sync::OnceLock;
        static RT: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
        static POOL: OnceLock<PgPool> = OnceLock::new();
        let rt = RT.get_or_init(|| {
            tokio::runtime::Builder::new_multi_thread()
                .enable_all()
                .build()
                .expect("无法创建测试用 Tokio 运行时")
        });
        POOL.get_or_init(|| {
            rt.block_on(async {
                PgPoolOptions::new()
                    .max_connections(1)
                    .connect_lazy("postgres://postgres:postgres@localhost:5432/test")
                    .expect("无法解析测试数据库 URL")
            })
        })
    }

    #[test]
    fn test_controlled_subqueries_preserve_nested_placeholder_order() {
        let pool = make_sync_test_pool();
        let paid_order = Subquery::new("orders", "id")
            .expect("合法子查询")
            .where_column("orders.user_id", "=", "users.id")
            .expect("合法关联列")
            .where_value("orders.status", "=", "paid")
            .expect("合法绑定条件");
        let active_user = Subquery::new("memberships", "user_id")
            .expect("合法子查询")
            .where_value("memberships.active", "=", true)
            .expect("合法绑定条件");
        let banned_user = Subquery::new("bans", "id")
            .expect("合法子查询")
            .where_column("bans.user_id", "=", "users.id")
            .expect("合法关联列")
            .where_value("bans.reason", "=", "fraud")
            .expect("合法绑定条件");

        let builder = QueryBuilder::new(pool, "users", false)
            .where_and(
                yang_db::field!("users.tenant_id"),
                yang_db::CompareOp::Eq,
                7,
            )
            .expect("固定受控条件应合法")
            .where_exists(paid_order)
            .where_in_subquery(yang_db::field!("users.id"), active_user)
            .where_not_exists(banned_user);
        let mut generator = SqlGenerator::new();
        generator.build_select(&builder).expect("子查询应可渲染");

        assert_eq!(
            generator.get_sql(),
            "SELECT * FROM \"users\" WHERE (\"users\".\"tenant_id\" = $1 AND EXISTS (SELECT \"id\" FROM \"orders\" WHERE \"orders\".\"user_id\" = \"users\".\"id\" AND \"orders\".\"status\" = $2) AND \"users\".\"id\" IN (SELECT \"user_id\" FROM \"memberships\" WHERE \"memberships\".\"active\" = $3) AND NOT EXISTS (SELECT \"id\" FROM \"bans\" WHERE \"bans\".\"user_id\" = \"users\".\"id\" AND \"bans\".\"reason\" = $4))"
        );
        assert!(
            matches!(generator.get_params(), [SqlValue::Int(7), SqlValue::String(status), SqlValue::Bool(true), SqlValue::String(reason)] if status == "paid" && reason == "fraud")
        );
    }

    #[test]
    fn test_controlled_subqueries_reject_adversarial_structure_before_rendering() {
        for payload in [
            "",
            "orders; DROP TABLE users",
            "orders --",
            "a.b",
            "orders\0",
        ] {
            assert!(
                Subquery::new(payload, "id").is_err(),
                "非法表名被接受: {payload:?}"
            );
        }
        for payload in ["", "id) FROM users --", "COUNT(*)", "a.b.c", "id\0"] {
            assert!(
                Subquery::new("orders", payload).is_err(),
                "非法投影被接受: {payload:?}"
            );
        }
        assert!(Subquery::new("orders", "id")
            .expect("合法子查询")
            .where_column("orders.user_id", "= 1 OR 1=1 --", "users.id")
            .is_err());
        assert!(Subquery::new("orders", "id")
            .expect("合法子查询")
            .where_value("orders.status --", "=", "paid")
            .is_err());
        assert!(crate::FieldRef::new("users.id) OR 1=1 --").is_err());
    }

    #[test]
    fn test_union_all_keeps_branch_scope_and_numbered_parameter_order() {
        let pool = make_sync_test_pool();
        let branch = QueryBuilder::new(pool, "archived_users", false)
            .field(yang_db::field!("id"))
            .field(yang_db::field!("kind"))
            .where_and(yang_db::field!("tenant_id"), yang_db::CompareOp::Eq, 8)
            .expect("固定受控条件应合法")
            .order(yang_db::field!("id"), yang_db::SortOrder::Desc)
            .limit(2);
        let builder = QueryBuilder::new(pool, "users", false)
            .field(yang_db::field!("id"))
            .field(yang_db::field!("kind"))
            .where_and(yang_db::field!("tenant_id"), yang_db::CompareOp::Eq, 7)
            .expect("固定受控条件应合法")
            .union_all(branch)
            .expect("输出列数一致")
            .order(yang_db::field!("id"), yang_db::SortOrder::Asc)
            .limit(5);
        let mut generator = SqlGenerator::new();
        generator
            .build_select(&builder)
            .expect("UNION ALL 应可渲染");

        assert_eq!(generator.get_sql(), "SELECT \"id\", \"kind\" FROM \"users\" WHERE \"tenant_id\" = $1 UNION ALL (SELECT \"id\", \"kind\" FROM \"archived_users\" WHERE \"tenant_id\" = $2 ORDER BY \"id\" DESC LIMIT 2) ORDER BY \"id\" ASC LIMIT 5");
        assert!(matches!(
            generator.get_params(),
            [SqlValue::Int(7), SqlValue::Int(8)]
        ));
    }

    #[test]
    fn test_union_rejects_unknown_or_mismatched_output_and_bad_branch_table() {
        let pool = make_sync_test_pool();
        assert!(QueryBuilder::new(pool, "users", false)
            .union(QueryBuilder::new(pool, "archive", false))
            .is_err());
        assert!(QueryBuilder::new(pool, "users", false)
            .field(yang_db::field!("id"))
            .union(
                QueryBuilder::new(pool, "archive", false)
                    .field(yang_db::field!("id"))
                    .field(yang_db::field!("kind")),
            )
            .is_err());
        let builder = QueryBuilder::new(pool, "users", false)
            .field(yang_db::field!("id"))
            .union(
                QueryBuilder::new(pool, "archive; DROP TABLE users", false)
                    .field(yang_db::field!("id")),
            )
            .expect("列数一致");
        let mut generator = SqlGenerator::new();
        assert!(generator.build_select(&builder).is_err());
        assert!(generator.get_params().is_empty());
    }

    #[test]
    fn test_transaction_row_lock_rendering_is_typed_and_numbered() {
        let builder = QueryBuilder::new(make_sync_test_pool(), "accounts", false)
            .field(yang_db::field!("balance"))
            .where_and(yang_db::field!("id"), yang_db::CompareOp::Eq, 42)
            .expect("固定受控条件应合法")
            .limit(1);
        let (sql, params) = builder
            .render_for_transaction(Some(crate::RowLock::ForUpdate))
            .expect("事务锁查询应可渲染");
        assert_eq!(
            sql,
            "SELECT \"balance\" FROM \"accounts\" WHERE \"id\" = $1 LIMIT 1 FOR UPDATE"
        );
        assert!(matches!(params.as_slice(), [SqlValue::Int(42)]));
    }

    #[test]
    fn test_transaction_row_lock_rejects_unsupported_query_shapes() {
        let pool = make_sync_test_pool();
        let grouped = QueryBuilder::new(pool, "accounts", false)
            .expr(crate::SelectExpr::count_all())
            .group(yang_db::field!("tenant_id"));
        assert!(grouped
            .render_for_transaction(Some(crate::RowLock::ForShare))
            .is_err());

        let union = QueryBuilder::new(pool, "accounts", false)
            .field(yang_db::field!("id"))
            .union(QueryBuilder::new(pool, "archived_accounts", false).field(yang_db::field!("id")))
            .expect("列数一致的 UNION 应构建成功");
        assert!(union
            .render_for_transaction(Some(crate::RowLock::ForUpdate))
            .is_err());
    }

    #[tokio::test]
    async fn test_atomic_update_rejects_missing_where_and_adversarial_field_before_io() {
        let pool = PgPoolOptions::new()
            .max_connections(1)
            .connect_lazy("postgres://postgres:postgres@localhost:5432/test")
            .expect("合法测试 URL");
        let missing_where = QueryBuilder::new(&pool, "accounts", false)
            .increment(yang_db::field!("balance"), 1)
            .await;
        assert!(matches!(
            missing_where,
            Err(crate::DbError::MissingWhereClause)
        ));

        assert!(crate::FieldRef::new("balance = 0; DROP TABLE accounts --").is_err());
    }

    #[test]
    fn test_atomic_update_renderer_binds_negative_amount_before_where_params() {
        let mut generator = SqlGenerator::new();
        generator
            .build_arithmetic_update(
                "accounts",
                "balance",
                ArithmeticOperator::Add,
                -3,
                &[Condition::Eq("id".to_string(), SqlValue::Int(9))],
            )
            .expect("原子更新应可渲染");
        assert_eq!(
            generator.get_sql(),
            "UPDATE \"accounts\" SET \"balance\" = \"balance\" + $1 WHERE \"id\" = $2"
        );
        assert!(matches!(
            generator.get_params(),
            [SqlValue::Int(-3), SqlValue::Int(9)]
        ));
    }

    #[test]
    fn test_identifier_apis_quote_every_structural_fragment() {
        let pool = make_sync_test_pool();
        let builder = QueryBuilder::new(pool, "users", false)
            .field(yang_db::field!("users.id"))
            .expr(crate::SelectExpr::count_all().alias(yang_db::field!("cnt")))
            .join(
                yang_db::table!("profiles"),
                yang_db::field!("users.id"),
                yang_db::field!("profiles.user_id"),
            )
            .group(yang_db::field!("users.id"))
            .order(yang_db::field!("users.id"), yang_db::SortOrder::Asc);

        let sql = builder.try_to_sql().expect("安全 API 应生成 SQL");
        assert!(sql.contains("SELECT \"users\".\"id\", COUNT(*) AS \"cnt\""));
        assert!(
            sql.contains("INNER JOIN \"profiles\" ON \"users\".\"id\" = \"profiles\".\"user_id\"")
        );
        assert!(sql.contains("GROUP BY \"users\".\"id\""));
        assert!(sql.contains("ORDER BY \"users\".\"id\" ASC"));
    }

    #[test]
    fn test_identifier_apis_reject_adversarial_fragments() {
        let payloads = [
            "",
            ".id",
            "users.",
            "a.b.c",
            "users.id --",
            "users/*x*/.id",
            "用户.id",
            "users.\"id\"",
            "users.id\0",
        ];

        for payload in payloads {
            assert!(crate::FieldRef::new(payload).is_err());
        }
        assert!(crate::TableRef::new("profiles p").is_err());
    }

    #[test]
    fn test_try_to_sql_surfaces_invalid_table_identifier() {
        let pool = make_sync_test_pool();
        let builder = QueryBuilder::new(pool, "users; DROP TABLE users", false);
        let result = builder.try_to_sql();

        assert!(matches!(result, Err(crate::DbError::InvalidArgument(_))));
    }

    #[test]
    fn test_try_to_sql_rejects_invalid_condition_identifier() {
        assert!(crate::FieldRef::new("id;DROP").is_err());
    }

    #[test]
    fn test_try_to_sql_accepts_qualified_where_and_having_identifiers() {
        let pool = make_sync_test_pool();
        let builder = QueryBuilder::new(pool, "users", false)
            .where_and(
                yang_db::field!("users.status"),
                yang_db::CompareOp::Eq,
                1i64,
            )
            .expect("固定受控条件应合法")
            .group(yang_db::field!("users.id"))
            .having_cond(
                yang_db::field!("users.score"),
                yang_db::CompareOp::Gt,
                10i64,
            )
            .expect("固定受控条件应合法");

        let sql = builder
            .try_to_sql()
            .expect("合法的两段限定条件字段应生成 SQL");

        assert!(sql.contains("WHERE \"users\".\"status\" = $1"));
        assert!(sql.contains("HAVING \"users\".\"score\" > $2"));
    }

    #[test]
    fn test_try_to_sql_rejects_malicious_qualified_where_and_having_identifiers() {
        let invalid_fields = [
            "",
            ".id",
            "users.",
            "a.b.c",
            "users.id;DROP",
            "users.id --",
            "users.\"id\"",
            "COUNT(users.id)",
        ];

        for field in invalid_fields {
            assert!(crate::FieldRef::new(field).is_err());
        }
    }

    #[test]
    fn test_try_to_sql_surfaces_missing_group_by() {
        let pool = make_sync_test_pool();
        let builder = QueryBuilder::new(pool, "orders", false)
            .having_cond(yang_db::field!("cnt"), yang_db::CompareOp::Gt, 5i64)
            .expect("固定受控条件应合法");
        let result = builder.try_to_sql();

        assert!(matches!(result, Err(crate::DbError::MissingGroupByClause)));
    }

    #[test]
    fn test_try_to_sql_rejects_empty_in_condition() {
        let pool = make_sync_test_pool();
        let builder = QueryBuilder::new(pool, "users", false)
            .where_in(yang_db::field!("id"), Vec::<i64>::new());
        let result = builder.try_to_sql();

        assert!(matches!(result, Err(crate::DbError::InvalidArgument(_))));
    }

    #[test]
    fn test_try_to_sql_rejects_empty_boolean_condition() {
        let pool = make_sync_test_pool();
        let mut builder = QueryBuilder::new(pool, "users", false);
        builder.conditions.push(Condition::And(vec![]));
        let result = builder.try_to_sql();

        assert!(matches!(result, Err(crate::DbError::InvalidArgument(_))));
    }

    #[test]
    fn test_to_sql_does_not_fallback_to_raw_untrusted_table() {
        let pool = make_sync_test_pool();
        let builder = QueryBuilder::new(pool, "users; DROP TABLE users", false);
        let sql = builder.to_sql();

        assert_eq!(sql, "/* SQL generation failed */");
        assert!(!sql.contains("DROP TABLE"));
        assert!(!sql.contains("users;"));
    }

    /// 构造仅含一个字段标记的空 field_types
    fn empty_types() -> HashMap<String, FieldType> {
        HashMap::new()
    }
    // PLACEHOLDER_TEST_CASES

    #[test]
    fn test_sql_generator_new_empty() {
        let generator = SqlGenerator::new();
        assert_eq!(generator.get_sql(), "");
        assert_eq!(generator.get_params().len(), 0);
    }

    #[test]
    fn test_build_insert_uses_dollar_placeholders() {
        let mut g = SqlGenerator::new();
        let data = serde_json::json!({"name": "张三", "age": 25});
        g.build_insert("users", &data, &empty_types()).unwrap();
        let sql = g.get_sql();
        // serde_json 默认按 key 字母序:age 在前、name 在后
        assert_eq!(
            sql,
            "INSERT INTO \"users\" (\"age\", \"name\") VALUES ($1, $2)"
        );
        // INSERT 本身不含 RETURNING(由 insert() 方法在外部追加)
        assert!(!sql.contains("RETURNING"));
        assert_eq!(g.get_params().len(), 2);
    }

    #[test]
    fn test_build_insert_inlines_null_without_placeholder() {
        let mut g = SqlGenerator::new();
        let data = serde_json::json!({"name": "张三", "deleted_at": null});
        g.build_insert("users", &data, &empty_types()).unwrap();
        let sql = g.get_sql();
        // 字母序:deleted_at(NULL 内联) 在前、name($1) 在后;NULL 不占占位符编号
        assert_eq!(
            sql,
            "INSERT INTO \"users\" (\"deleted_at\", \"name\") VALUES (NULL, $1)"
        );
        assert_eq!(g.get_params().len(), 1);
    }

    #[test]
    fn test_build_update_set_then_where_numbering_continues() {
        let mut g = SqlGenerator::new();
        let data = serde_json::json!({"name": "李四", "age": 30});
        let conditions = vec![Condition::Eq("id".to_string(), SqlValue::Int(1))];
        g.build_update("users", &data, &empty_types(), &conditions)
            .unwrap();
        let sql = g.get_sql();
        // 字母序:age=$1, name=$2;WHERE 接续为 $3
        assert_eq!(
            sql,
            "UPDATE \"users\" SET \"age\" = $1, \"name\" = $2 WHERE \"id\" = $3"
        );
        assert_eq!(g.get_params().len(), 3);
    }

    /// DB-3:单行 UPDATE 的 SET 子句对 NULL 内联字面量,不占占位符编号。
    #[test]
    fn test_build_update_inlines_null_in_set() {
        let mut g = SqlGenerator::new();
        // description 设为 NULL,name 为普通值
        let data = serde_json::json!({"description": serde_json::Value::Null, "name": "张三"});
        let conditions = vec![Condition::Eq("id".to_string(), SqlValue::Int(1))];
        g.build_update("users", &data, &empty_types(), &conditions)
            .unwrap();
        let sql = g.get_sql();
        // 字母序:description 内联 NULL(不占编号),name=$1,WHERE 接续 $2
        assert_eq!(
            sql,
            "UPDATE \"users\" SET \"description\" = NULL, \"name\" = $1 WHERE \"id\" = $2"
        );
        // NULL 不压参数:仅 name + WHERE id 两个参数
        assert_eq!(g.get_params().len(), 2);
    }

    #[test]
    fn test_build_delete_dollar_placeholder() {
        let mut g = SqlGenerator::new();
        let conditions = vec![Condition::Eq("id".to_string(), SqlValue::Int(7))];
        g.build_delete("users", &conditions).unwrap();
        assert_eq!(g.get_sql(), "DELETE FROM \"users\" WHERE \"id\" = $1");
        assert_eq!(g.get_params().len(), 1);
    }

    #[test]
    fn test_build_delete_requires_where() {
        let mut g = SqlGenerator::new();
        let err = g.build_delete("users", &[]).unwrap_err();
        assert!(matches!(err, crate::error::DbError::MissingWhereClause));
    }

    #[test]
    fn test_build_upsert_on_conflict_excluded() {
        let mut g = SqlGenerator::new();
        let data = serde_json::json!({"id": 1, "name": "张三", "email": "z@example.com"});
        let conflict = vec!["id".to_string()];
        g.build_upsert("users", &data, &empty_types(), &conflict)
            .unwrap();
        let sql = g.get_sql();
        // 字母序字段:email($1), id($2), name($3)
        assert!(sql.starts_with(
            "INSERT INTO \"users\" (\"email\", \"id\", \"name\") VALUES ($1, $2, $3)"
        ));
        assert!(sql.contains("ON CONFLICT (\"id\") DO UPDATE SET"));
        // 冲突列 id 不参与更新,其余列用 EXCLUDED.col
        assert!(sql.contains("\"name\" = EXCLUDED.\"name\""));
        assert!(sql.contains("\"email\" = EXCLUDED.\"email\""));
        assert!(!sql.contains("\"id\" = EXCLUDED.\"id\""));
        assert_eq!(g.get_params().len(), 3);
    }

    #[test]
    fn test_build_upsert_empty_conflict_do_nothing() {
        let mut g = SqlGenerator::new();
        let data = serde_json::json!({"name": "张三"});
        g.build_upsert("users", &data, &empty_types(), &[]).unwrap();
        assert!(g.get_sql().contains("ON CONFLICT DO NOTHING"));
    }

    #[test]
    fn test_build_insert_batch_sequential_numbering() {
        let mut g = SqlGenerator::new();
        let list = vec![
            serde_json::json!({"name": "a", "age": 1}),
            serde_json::json!({"name": "b", "age": 2}),
        ];
        g.build_insert_batch("users", &list, &empty_types())
            .unwrap();
        let sql = g.get_sql();
        // 字母序字段:age, name;占位符跨记录连续递增
        assert_eq!(
            sql,
            "INSERT INTO \"users\" (\"age\", \"name\") VALUES ($1, $2), ($3, $4)"
        );
        assert_eq!(g.get_params().len(), 4);
    }

    #[test]
    fn test_sum_expr_uses_double_precision() {
        let pool = make_sync_test_pool();
        // 通过 fetch_scalar 路径间接构造的表达式无法静态读取,这里直接断言生成片段
        let sql = QueryBuilder::new(pool, "orders", false)
            .expr(crate::SelectExpr::sum(yang_db::field!("amount")).cast_double())
            .to_sql();
        assert!(sql.contains("DOUBLE PRECISION"));
        assert!(sql.contains("FROM \"orders\""));
    }

    #[test]
    fn test_avg_expr_uses_double_precision() {
        let expr = format!("CAST(AVG({}) AS DOUBLE PRECISION)", "score");
        assert!(expr.contains("DOUBLE PRECISION"));
    }

    #[test]
    fn test_to_sql_select_basic() {
        let pool = make_sync_test_pool();
        let sql = QueryBuilder::new(pool, "users", false)
            .field(yang_db::field!("id"))
            .field(yang_db::field!("name"))
            .to_sql();
        assert_eq!(sql, "SELECT \"id\", \"name\" FROM \"users\"");
    }

    #[test]
    fn test_to_sql_where_uses_dollar() {
        let pool = make_sync_test_pool();
        let sql = QueryBuilder::new(pool, "users", false)
            .where_and(yang_db::field!("id"), yang_db::CompareOp::Eq, 1)
            .expect("固定受控条件应合法")
            .to_sql();
        assert_eq!(sql, "SELECT * FROM \"users\" WHERE \"id\" = $1");
    }

    #[test]
    fn test_default_returning_and_conflict_columns() {
        let pool = make_sync_test_pool();
        let qb = QueryBuilder::new(pool, "users", false);
        assert_eq!(qb.returning, "id");
        assert_eq!(qb.conflict_columns, vec!["id".to_string()]);
        let qb2 = qb
            .returning(yang_db::field!("uid"))
            .on_conflict(&[yang_db::field!("email"), yang_db::field!("tenant_id")]);
        assert_eq!(qb2.returning, "uid");
        assert_eq!(
            qb2.conflict_columns,
            vec!["email".to_string(), "tenant_id".to_string()]
        );
    }
}