sz-orm-sqlx 2.3.0

sqlx adapter: MySQL, PostgreSQL, SQLite backend via sqlx crate
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
//! sqlx 后端适配器实现
//!
//! 为 MySQL、PostgreSQL、SQLite 分别实现 Connection 和 ConnectionFactory。
//! 不使用 sqlx::Any 以避免其类型限制和生命周期问题。
//!
//! 关键设计:
//! Connection trait 已手动解糖(不使用 `#[async_trait]`),所有 async 方法
//! 使用单一生命周期 `'a`(绑定 `&'a mut self` 和 `&'a str`),而非 HRTB。
//! 这样 sqlx::Executor 对 `&'c mut XxxConnection` 的 impl(针对具体 `'c`)
//! 即可满足约束,避免 "implementation of Executor is not general enough" 错误。

use async_trait::async_trait;
use futures::StreamExt;
use sqlx::{Column, Executor, Row, TypeInfo};
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::str::FromStr;
use std::sync::Arc;
use sz_orm_core::{ColType, Connection, ConnectionFactory, DbError, QueryRows, QueryValues, Value};

use crate::error::map_sqlx_error;

/// 判断 SQL 是否需要走 raw_sql 路径
/// MySQL prepared statement 协议不支持 BEGIN/COMMIT/ROLLBACK/SAVEPOINT 等命令
fn needs_raw_sql(sql: &str) -> bool {
    let trimmed = sql.trim_start();
    let upper = trimmed.to_uppercase();
    upper.starts_with("BEGIN")
        || upper.starts_with("COMMIT")
        || upper.starts_with("ROLLBACK")
        || upper.starts_with("SAVEPOINT")
        || upper.starts_with("RELEASE")
        || upper.starts_with("SET ")
        || upper.starts_with("USE ")
        || upper.starts_with("START TRANSACTION")
}

// ===================== SQLite 适配器 =====================

// 注:sqlx 0.9 起 Executor trait 要求 'static lifetime,
// 原先的 execute_sqlite_boxed / query_sqlite_boxed 已内联到调用点。
// 见 SqlxSqliteConnection::execute / query 实现。

// 注:原 row_to_value_sqlite(按 type_info().name() 字符串 match)已被
// row_to_value_with_coltype_sqlite(按预解析 ColType 枚举分派)取代,
// 性能更优且避免每行字符串比较。详见该函数。

/// SQLite: 使用预解析的 ColType 进行类型分派(避免每行字符串 match)
///
/// 调用方预先通过 [`ColType::parse_sqlite`] 解析列类型,
/// 后续行直接用枚举分派(编译器优化为跳转表),避免每行每列的字符串比较。
///
/// **注意**:必须使用 `parse_sqlite` 而非通用 `from_type_name`:SQLite 的 INTEGER 类型
/// 实际为 64 位动态存储,通用映射会错误地归类为 I32,导致数值截断。
fn row_to_value_with_coltype_sqlite(
    row: &sqlx::sqlite::SqliteRow,
    ordinal: usize,
    col_type: ColType,
) -> Value {
    match col_type {
        ColType::Bool => match row.try_get::<Option<bool>, usize>(ordinal) {
            Ok(v) => v.map(Value::Bool).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::I8 => match row.try_get::<Option<i8>, usize>(ordinal) {
            Ok(v) => v.map(Value::I8).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::I16 => match row.try_get::<Option<i16>, usize>(ordinal) {
            Ok(v) => v.map(Value::I16).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::I32 => match row.try_get::<Option<i32>, usize>(ordinal) {
            Ok(v) => v.map(Value::I32).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::I64 => match row.try_get::<Option<i64>, usize>(ordinal) {
            Ok(v) => v.map(Value::I64).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::U8 => match row.try_get::<Option<u8>, usize>(ordinal) {
            Ok(v) => v.map(Value::U8).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::U16 => match row.try_get::<Option<u16>, usize>(ordinal) {
            Ok(v) => v.map(Value::U16).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::U32 => match row.try_get::<Option<u32>, usize>(ordinal) {
            Ok(v) => v.map(Value::U32).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        // SQLite 无原生 u64,按 i64 解码
        ColType::U64 => match row.try_get::<Option<i64>, usize>(ordinal) {
            Ok(v) => v.map(Value::I64).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::F32 => match row.try_get::<Option<f32>, usize>(ordinal) {
            Ok(v) => v.map(Value::F32).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::F64 => match row.try_get::<Option<f64>, usize>(ordinal) {
            Ok(v) => v.map(Value::F64).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::Decimal => match row.try_get::<Option<String>, usize>(ordinal) {
            Ok(v) => v.map(Value::Decimal).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::String => match row.try_get::<Option<String>, usize>(ordinal) {
            Ok(v) => v.map(Value::String).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::Bytes => match row.try_get::<Option<Vec<u8>>, usize>(ordinal) {
            Ok(v) => v.map(Value::Bytes).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        // SQLite 中 DATE/DATETIME/TIME/JSON/UUID 通常以 TEXT 存储
        ColType::Date | ColType::DateTime | ColType::Time | ColType::Json | ColType::Uuid => {
            match row.try_get::<Option<String>, usize>(ordinal) {
                Ok(v) => v.map(Value::String).unwrap_or(Value::Null),
                Err(_) => Value::Null,
            }
        }
        ColType::Unknown => {
            // 未知类型,按 bool → i64 → f64 → String 顺序回退
            if let Ok(v) = row.try_get::<Option<bool>, usize>(ordinal) {
                return v.map(Value::Bool).unwrap_or(Value::Null);
            }
            if let Ok(v) = row.try_get::<Option<i64>, usize>(ordinal) {
                return v.map(Value::I64).unwrap_or(Value::Null);
            }
            if let Ok(v) = row.try_get::<Option<f64>, usize>(ordinal) {
                return v.map(Value::F64).unwrap_or(Value::Null);
            }
            if let Ok(v) = row.try_get::<Option<String>, usize>(ordinal) {
                return v.map(Value::String).unwrap_or(Value::Null);
            }
            Value::Null
        }
        // ColType 标记为 #[non_exhaustive],未来新增变体按 Unknown 处理
        _ => Value::Null,
    }
}

pub struct SqlitePoolHandle {
    pool: sqlx::SqlitePool,
}

impl SqlitePoolHandle {
    pub async fn connect(url: &str) -> Result<Self, DbError> {
        // SQLite 生产配置:WAL + NORMAL 同步 + 5s 忙等 + 256MB mmap
        // - WAL:写不阻塞读,崩溃后通过 WAL 恢复,远比 DELETE 模式安全
        // - Synchronous=Normal:WAL 模式下仅在 checkpoint 时 fsync,性能 ~2x 于 Full
        // - busy_timeout=5s:避免 "database is locked" 误报
        // - mmap_size=256MB:大结果集减少 syscall,提升读取吞吐
        let opts = sqlx::sqlite::SqliteConnectOptions::from_str(url)
            .map_err(map_sqlx_error)?
            .journal_mode(sqlx::sqlite::SqliteJournalMode::Wal)
            .synchronous(sqlx::sqlite::SqliteSynchronous::Normal)
            .busy_timeout(std::time::Duration::from_secs(5))
            .pragma("mmap_size", "268435456");
        let pool = sqlx::sqlite::SqlitePoolOptions::new()
            .max_connections(10)
            .acquire_timeout(std::time::Duration::from_secs(30))
            .idle_timeout(Some(std::time::Duration::from_secs(600)))
            .max_lifetime(Some(std::time::Duration::from_secs(1800)))
            .connect_with(opts)
            .await
            .map_err(map_sqlx_error)?;
        Ok(Self { pool })
    }

    pub fn from_pool(pool: sqlx::SqlitePool) -> Self {
        Self { pool }
    }

    pub fn pool(&self) -> &sqlx::SqlitePool {
        &self.pool
    }
}

pub struct SqlxSqliteConnectionFactory {
    pool: Arc<SqlitePoolHandle>,
}

impl SqlxSqliteConnectionFactory {
    pub fn new(pool: Arc<SqlitePoolHandle>) -> Self {
        Self { pool }
    }
}

#[async_trait]
impl ConnectionFactory for SqlxSqliteConnectionFactory {
    async fn create(&self) -> Result<Box<dyn Connection>, DbError> {
        let conn = self.pool.pool.acquire().await.map_err(map_sqlx_error)?;
        Ok(Box::new(SqlxSqliteConnection {
            conn: Some(conn),
            connected: true,
            in_transaction: false,
        }))
    }
}

pub struct SqlxSqliteConnection {
    conn: Option<sqlx::pool::PoolConnection<sqlx::Sqlite>>,
    connected: bool,
    in_transaction: bool,
}

impl Connection for SqlxSqliteConnection {
    fn execute<'a>(
        &'a mut self,
        sql: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<u64, DbError>> + Send + 'a>> {
        Box::pin(async move {
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            // sqlx 0.9: PoolConnection 不再实现 Executor,需通过 DerefMut 解引用到内部连接
            // sqlx 0.9: SqlSafeStr 只对 &'static str 直接实现,非 'static 的 &str 需用 AssertSqlSafe 包装
            let result = if needs_raw_sql(sql) {
                (&mut *pool_conn)
                    .execute(sqlx::raw_sql(sqlx::AssertSqlSafe(sql)))
                    .await
            } else {
                (&mut *pool_conn).execute(sqlx::AssertSqlSafe(sql)).await
            };
            self.conn = Some(pool_conn);

            match result {
                Ok(r) => Ok(r.rows_affected()),
                Err(e) => {
                    let db_err = map_sqlx_error(e);
                    if matches!(db_err, DbError::ConnectionError(_) | DbError::IoError(_)) {
                        self.connected = false;
                    }
                    Err(db_err)
                }
            }
        })
    }

    fn query<'a>(
        &'a mut self,
        sql: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<HashMap<String, Value>>, DbError>> + Send + 'a>>
    {
        Box::pin(async move {
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            // sqlx 0.9: PoolConnection 不再实现 Executor,需通过 DerefMut 解引用到内部连接
            // sqlx 0.9: SqlSafeStr 只对 &'static str 直接实现,非 'static 的 &str 需用 AssertSqlSafe 包装
            let rows_result = (&mut *pool_conn).fetch_all(sqlx::AssertSqlSafe(sql)).await;
            self.conn = Some(pool_conn);

            let rows = rows_result.map_err(map_sqlx_error)?;
            if rows.is_empty() {
                return Ok(Vec::new());
            }
            // 预解析列类型(只在第一行解析,后续行复用,避免每行字符串 match)
            // SQLite 专用解析:INTEGER 映射为 I64(SQLite 整数动态存储,可容纳 64 位)
            let col_types: Vec<ColType> = rows[0]
                .columns()
                .iter()
                .map(|col| ColType::parse_sqlite(col.type_info().name()))
                .collect();
            let mut result = Vec::with_capacity(rows.len());
            for row in &rows {
                let mut record = HashMap::with_capacity(col_types.len());
                for (i, col) in row.columns().iter().enumerate() {
                    let name = col.name().to_string();
                    let value = row_to_value_with_coltype_sqlite(row, i, col_types[i]);
                    record.insert(name, value);
                }
                result.push(record);
            }
            Ok(result)
        })
    }

    fn begin_transaction<'a>(
        &'a mut self,
    ) -> Pin<Box<dyn Future<Output = Result<(), DbError>> + Send + 'a>> {
        Box::pin(async move {
            if self.in_transaction {
                return Err(DbError::Internal("transaction already started".to_string()));
            }
            self.execute("BEGIN").await?;
            self.in_transaction = true;
            Ok(())
        })
    }

    fn commit<'a>(&'a mut self) -> Pin<Box<dyn Future<Output = Result<(), DbError>> + Send + 'a>> {
        Box::pin(async move {
            if self.in_transaction {
                self.execute("COMMIT").await?;
                self.in_transaction = false;
            }
            Ok(())
        })
    }

    fn rollback<'a>(
        &'a mut self,
    ) -> Pin<Box<dyn Future<Output = Result<(), DbError>> + Send + 'a>> {
        Box::pin(async move {
            if self.in_transaction {
                let result = self.execute("ROLLBACK").await;
                self.in_transaction = false;
                result.map(|_| ())
            } else {
                Ok(())
            }
        })
    }

    fn is_connected(&self) -> bool {
        self.connected
    }

    fn ping<'a>(&'a mut self) -> Pin<Box<dyn Future<Output = bool> + Send + 'a>> {
        Box::pin(async move {
            match self.execute("SELECT 1").await {
                Ok(_) => true,
                Err(_) => {
                    self.connected = false;
                    false
                }
            }
        })
    }

    fn close<'a>(&'a mut self) -> Pin<Box<dyn Future<Output = Result<(), DbError>> + Send + 'a>> {
        Box::pin(async move {
            if let Some(conn) = self.conn.take() {
                drop(conn);
            }
            self.connected = false;
            self.in_transaction = false;
            Ok(())
        })
    }

    /// SQLite 参数绑定执行(INSERT/UPDATE/DELETE)
    ///
    /// 使用 sqlx prepared statement 绑定参数,避免 SQL 注入与字符串转义开销。
    /// 对 `Value::Bool`/`I8`..=`I64`/`U8`..=`U64`/`F32`/`F64`/`String`/`Bytes` 直接 bind;
    /// 其他类型(Date/DateTime/Json/Array/Object)回退为 `to_string()` 后以 TEXT 绑定。
    fn execute_with_params<'a>(
        &'a mut self,
        sql: &'a str,
        params: &'a [Value],
    ) -> Pin<Box<dyn Future<Output = Result<u64, DbError>> + Send + 'a>> {
        Box::pin(async move {
            if needs_raw_sql(sql) || params.is_empty() {
                return self.execute(sql).await;
            }
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            let mut q = sqlx::query(sqlx::AssertSqlSafe(sql));
            for v in params {
                q = match v {
                    Value::Null => q.bind(None::<i64>),
                    Value::Bool(b) => q.bind(*b),
                    Value::I8(n) => q.bind(*n),
                    Value::I16(n) => q.bind(*n),
                    Value::I32(n) => q.bind(*n),
                    Value::I64(n) => q.bind(*n),
                    Value::U8(n) => q.bind(*n),
                    Value::U16(n) => q.bind(*n),
                    Value::U32(n) => q.bind(*n),
                    Value::U64(n) => q.bind(*n as i64),
                    Value::F32(f) => q.bind(*f),
                    Value::F64(f) => q.bind(*f),
                    Value::String(s) => q.bind(s.as_str()),
                    Value::Decimal(s) => q.bind(s.as_str()),
                    Value::Bytes(b) => q.bind(b.as_slice()),
                    other => q.bind(other.to_string()),
                };
            }
            let result = q.execute(&mut *pool_conn).await;
            self.conn = Some(pool_conn);
            match result {
                Ok(r) => Ok(r.rows_affected()),
                Err(e) => {
                    let db_err = map_sqlx_error(e);
                    if matches!(db_err, DbError::ConnectionError(_) | DbError::IoError(_)) {
                        self.connected = false;
                    }
                    Err(db_err)
                }
            }
        })
    }

    /// SQLite 参数绑定查询(SELECT,HashMap 映射)
    ///
    /// 使用 sqlx prepared statement 绑定参数,结果按预解析 ColType 解码为
    /// `HashMap<String, Value>`。与 `query` 的区别仅在于参数绑定路径。
    fn query_with_params<'a>(
        &'a mut self,
        sql: &'a str,
        params: &'a [Value],
    ) -> Pin<Box<dyn Future<Output = Result<QueryRows, DbError>> + Send + 'a>> {
        Box::pin(async move {
            if params.is_empty() {
                return self.query(sql).await;
            }
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            let mut q = sqlx::query(sqlx::AssertSqlSafe(sql));
            for v in params {
                q = match v {
                    Value::Null => q.bind(None::<i64>),
                    Value::Bool(b) => q.bind(*b),
                    Value::I8(n) => q.bind(*n),
                    Value::I16(n) => q.bind(*n),
                    Value::I32(n) => q.bind(*n),
                    Value::I64(n) => q.bind(*n),
                    Value::U8(n) => q.bind(*n),
                    Value::U16(n) => q.bind(*n),
                    Value::U32(n) => q.bind(*n),
                    Value::U64(n) => q.bind(*n as i64),
                    Value::F32(f) => q.bind(*f),
                    Value::F64(f) => q.bind(*f),
                    Value::String(s) => q.bind(s.as_str()),
                    Value::Decimal(s) => q.bind(s.as_str()),
                    Value::Bytes(b) => q.bind(b.as_slice()),
                    other => q.bind(other.to_string()),
                };
            }
            let rows_result = q.fetch_all(&mut *pool_conn).await;
            self.conn = Some(pool_conn);
            let rows = rows_result.map_err(map_sqlx_error)?;
            if rows.is_empty() {
                return Ok(Vec::new());
            }
            // 预解析列类型(只在第一行解析,后续行复用)
            // SQLite 专用解析:INTEGER → I64
            let col_types: Vec<ColType> = rows[0]
                .columns()
                .iter()
                .map(|col| ColType::parse_sqlite(col.type_info().name()))
                .collect();
            let mut result = Vec::with_capacity(rows.len());
            for row in &rows {
                let mut record = HashMap::with_capacity(col_types.len());
                for (i, col) in row.columns().iter().enumerate() {
                    let name = col.name().to_string();
                    let value = row_to_value_with_coltype_sqlite(row, i, col_types[i]);
                    record.insert(name, value);
                }
                result.push(record);
            }
            Ok(result)
        })
    }

    /// SQLite 位置式查询(SELECT,无参数)
    ///
    /// 绕过 `HashMap<String, Value>` 行映射,返回 `(列名列表, 按列序号的值矩阵)`。
    /// 列名与 ColType 仅 `to_string`/解析一次,后续行复用;每行值按列序号直接 `Vec::push`,
    /// 无哈希计算与字符串克隆。适用于 SELECT ALL 大结果集场景。
    fn query_values<'a>(
        &'a mut self,
        sql: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<QueryValues, DbError>> + Send + 'a>> {
        Box::pin(async move {
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            let rows_result = (&mut *pool_conn).fetch_all(sqlx::AssertSqlSafe(sql)).await;
            self.conn = Some(pool_conn);
            let rows = rows_result.map_err(map_sqlx_error)?;
            if rows.is_empty() {
                return Ok((Vec::new(), Vec::new()));
            }
            let cols = rows[0].columns();
            let mut col_names: Vec<String> = Vec::with_capacity(cols.len());
            let mut col_types: Vec<ColType> = Vec::with_capacity(cols.len());
            for col in cols {
                col_names.push(col.name().to_string());
                col_types.push(ColType::parse_sqlite(col.type_info().name()));
            }
            let mut result_rows: Vec<Vec<Value>> = Vec::with_capacity(rows.len());
            for row in &rows {
                let mut row_values: Vec<Value> = Vec::with_capacity(col_names.len());
                for (idx, _) in col_names.iter().enumerate() {
                    row_values.push(row_to_value_with_coltype_sqlite(row, idx, col_types[idx]));
                }
                result_rows.push(row_values);
            }
            Ok((col_names, result_rows))
        })
    }

    /// SQLite 参数绑定位置式查询(SELECT)
    ///
    /// 叠加 prepared statement + 位置式映射 + ColType 预解析三重优化。
    fn query_values_with_params<'a>(
        &'a mut self,
        sql: &'a str,
        params: &'a [Value],
    ) -> Pin<Box<dyn Future<Output = Result<QueryValues, DbError>> + Send + 'a>> {
        Box::pin(async move {
            if params.is_empty() {
                return self.query_values(sql).await;
            }
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            let mut q = sqlx::query(sqlx::AssertSqlSafe(sql));
            for v in params {
                q = match v {
                    Value::Null => q.bind(None::<i64>),
                    Value::Bool(b) => q.bind(*b),
                    Value::I8(n) => q.bind(*n),
                    Value::I16(n) => q.bind(*n),
                    Value::I32(n) => q.bind(*n),
                    Value::I64(n) => q.bind(*n),
                    Value::U8(n) => q.bind(*n),
                    Value::U16(n) => q.bind(*n),
                    Value::U32(n) => q.bind(*n),
                    Value::U64(n) => q.bind(*n as i64),
                    Value::F32(f) => q.bind(*f),
                    Value::F64(f) => q.bind(*f),
                    Value::String(s) => q.bind(s.as_str()),
                    Value::Decimal(s) => q.bind(s.as_str()),
                    Value::Bytes(b) => q.bind(b.as_slice()),
                    other => q.bind(other.to_string()),
                };
            }
            let rows_result = q.fetch_all(&mut *pool_conn).await;
            self.conn = Some(pool_conn);
            let rows = rows_result.map_err(map_sqlx_error)?;
            if rows.is_empty() {
                return Ok((Vec::new(), Vec::new()));
            }
            let cols = rows[0].columns();
            let mut col_names: Vec<String> = Vec::with_capacity(cols.len());
            let mut col_types: Vec<ColType> = Vec::with_capacity(cols.len());
            for col in cols {
                col_names.push(col.name().to_string());
                col_types.push(ColType::parse_sqlite(col.type_info().name()));
            }
            let mut result_rows: Vec<Vec<Value>> = Vec::with_capacity(rows.len());
            for row in &rows {
                let mut row_values: Vec<Value> = Vec::with_capacity(col_names.len());
                for (idx, _) in col_names.iter().enumerate() {
                    row_values.push(row_to_value_with_coltype_sqlite(row, idx, col_types[idx]));
                }
                result_rows.push(row_values);
            }
            Ok((col_names, result_rows))
        })
    }

    /// SQLite 流式查询:逐行返回结果,避免大结果集 `fetch_all` 内存峰值
    ///
    /// 使用 `sqlx::query::fetch` 获取行流,逐行映射为 `HashMap<String, Value>`。
    /// 流正常消费完毕后连接归还 `self.conn`;若提前 drop 流,连接通过
    /// `PoolConnection::drop` 归还到 sqlx 池,但 `self.conn` 变为 `None`。
    fn query_stream<'a>(
        &'a mut self,
        sql: &'a str,
    ) -> Pin<Box<dyn futures::Stream<Item = Result<HashMap<String, Value>, DbError>> + Send + 'a>>
    {
        Box::pin(async_stream::try_stream! {
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            let mut row_stream = sqlx::query(sqlx::AssertSqlSafe(sql)).fetch(&mut *pool_conn);
            let mut col_types: Vec<ColType> = Vec::new();
            let mut col_names: Vec<String> = Vec::new();
            let mut first_row = true;
            while let Some(row_result) = row_stream.next().await {
                let row = row_result.map_err(map_sqlx_error)?;
                if first_row {
                    for col in row.columns() {
                        col_names.push(col.name().to_string());
                        col_types.push(ColType::parse_sqlite(col.type_info().name()));
                    }
                    first_row = false;
                }
                let mut record = HashMap::with_capacity(col_names.len());
                for (i, name) in col_names.iter().enumerate() {
                    let value = row_to_value_with_coltype_sqlite(&row, i, col_types[i]);
                    record.insert(name.clone(), value);
                }
                yield record;
            }
            // 显式释放 row_stream 对 pool_conn 的可变借用,否则借用检查器
            // 无法证明 row_stream 在移动 pool_conn 前已被销毁(E0505)
            drop(row_stream);
            self.conn = Some(pool_conn);
        })
    }
}

impl Drop for SqlxSqliteConnection {
    fn drop(&mut self) {
        if let Some(conn) = self.conn.take() {
            drop(conn);
        }
    }
}

/// SQLite 在线备份(使用 VACUUM INTO,要求 SQLite 3.27+)
///
/// 将当前数据库完整复制到目标路径,原数据库可继续读写(在线备份)。
/// 目标文件若已存在会报错。路径中的单引号会被转义以防 SQL 注入。
pub async fn sqlite_backup(
    conn: &mut SqlxSqliteConnection,
    dest_path: &str,
) -> Result<(), DbError> {
    let escaped_path = dest_path.replace('\'', "''");
    let sql = format!("VACUUM INTO '{}'", escaped_path);
    conn.execute(&sql).await?;
    Ok(())
}

// ===================== MySQL 适配器 =====================

// 注:sqlx 0.9 起 Executor trait 要求 'static lifetime,
// 原先的 execute_mysql_boxed / query_mysql_boxed 已内联到调用点。

fn row_to_value_mysql(row: &sqlx::mysql::MySqlRow, ordinal: usize) -> Value {
    use sqlx::TypeInfo;
    let type_name = row.columns()[ordinal].type_info().name();
    match type_name {
        "BOOLEAN" => match row.try_get::<Option<bool>, usize>(ordinal) {
            Ok(v) => v.map(Value::Bool).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        "TINYINT" | "TINYINT UNSIGNED" => match row.try_get::<Option<i8>, usize>(ordinal) {
            Ok(v) => v.map(Value::I8).unwrap_or(Value::Null),
            Err(_) => match row.try_get::<Option<u8>, usize>(ordinal) {
                Ok(v) => v.map(Value::U8).unwrap_or(Value::Null),
                Err(_) => Value::Null,
            },
        },
        "SMALLINT" | "SMALLINT UNSIGNED" => match row.try_get::<Option<i16>, usize>(ordinal) {
            Ok(v) => v.map(Value::I16).unwrap_or(Value::Null),
            Err(_) => match row.try_get::<Option<u16>, usize>(ordinal) {
                Ok(v) => v.map(Value::U16).unwrap_or(Value::Null),
                Err(_) => Value::Null,
            },
        },
        "INT" | "INT UNSIGNED" | "MEDIUMINT" | "MEDIUMINT UNSIGNED" => {
            match row.try_get::<Option<i32>, usize>(ordinal) {
                Ok(v) => v.map(Value::I32).unwrap_or(Value::Null),
                Err(_) => match row.try_get::<Option<u32>, usize>(ordinal) {
                    Ok(v) => v.map(Value::U32).unwrap_or(Value::Null),
                    Err(_) => Value::Null,
                },
            }
        }
        "BIGINT" | "BIGINT UNSIGNED" => match row.try_get::<Option<i64>, usize>(ordinal) {
            Ok(v) => v.map(Value::I64).unwrap_or(Value::Null),
            Err(_) => match row.try_get::<Option<u64>, usize>(ordinal) {
                Ok(v) => v.map(Value::U64).unwrap_or(Value::Null),
                Err(_) => Value::Null,
            },
        },
        "FLOAT" => match row.try_get::<Option<f32>, usize>(ordinal) {
            Ok(v) => v.map(Value::F32).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        "DOUBLE" => match row.try_get::<Option<f64>, usize>(ordinal) {
            Ok(v) => v.map(Value::F64).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        "VARCHAR" | "TEXT" | "CHAR" | "TINYTEXT" | "MEDIUMTEXT" | "LONGTEXT" | "ENUM" => {
            match row.try_get::<Option<String>, usize>(ordinal) {
                Ok(v) => v.map(Value::String).unwrap_or(Value::Null),
                Err(_) => Value::Null,
            }
        }
        "BLOB" | "TINYBLOB" | "MEDIUMBLOB" | "LONGBLOB" | "BINARY" | "VARBINARY" => {
            match row.try_get::<Option<Vec<u8>>, usize>(ordinal) {
                Ok(v) => v.map(Value::Bytes).unwrap_or(Value::Null),
                Err(_) => Value::Null,
            }
        }
        // DECIMAL/NUMERIC 使用 rust_decimal 解码,以字符串形式保留精度
        "DECIMAL" | "NUMERIC" | "NEWDECIMAL" => {
            match row.try_get::<Option<rust_decimal::Decimal>, usize>(ordinal) {
                Ok(Some(v)) => Value::Decimal(v.to_string()),
                Ok(None) => Value::Null,
                Err(_) => match row.try_get::<Option<String>, usize>(ordinal) {
                    Ok(v) => v.map(Value::String).unwrap_or(Value::Null),
                    Err(_) => Value::Null,
                },
            }
        }
        _ => {
            // 未知类型回退:i64 → f64 → bool → String
            if let Ok(v) = row.try_get::<Option<i64>, usize>(ordinal) {
                return v.map(Value::I64).unwrap_or(Value::Null);
            }
            if let Ok(v) = row.try_get::<Option<f64>, usize>(ordinal) {
                return v.map(Value::F64).unwrap_or(Value::Null);
            }
            if let Ok(v) = row.try_get::<Option<bool>, usize>(ordinal) {
                return v.map(Value::Bool).unwrap_or(Value::Null);
            }
            if let Ok(v) = row.try_get::<Option<String>, usize>(ordinal) {
                return v.map(Value::String).unwrap_or(Value::Null);
            }
            Value::Null
        }
    }
}

/// MySQL: 使用预解析的 ColType 进行类型分派(避免每行字符串 match)
///
/// 与 [`row_to_value_mysql`] 的区别:调用方预先通过 [`ColType::parse_mysql`] 解析列类型,
/// 后续行直接用枚举分派(编译器优化为跳转表),避免每行每列的字符串比较。
///
/// **注意**:必须使用 `parse_mysql` 而非通用 `from_type_name`:MySQL 协议报告的类型名
/// 包含 NEWDECIMAL/YEAR/ENUM/SET 等特有类型,通用映射无法识别。
fn row_to_value_with_coltype_mysql(
    row: &sqlx::mysql::MySqlRow,
    ordinal: usize,
    col_type: ColType,
) -> Value {
    match col_type {
        ColType::Bool => match row.try_get::<Option<bool>, usize>(ordinal) {
            Ok(v) => v.map(Value::Bool).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::I8 => match row.try_get::<Option<i8>, usize>(ordinal) {
            Ok(v) => v.map(Value::I8).unwrap_or(Value::Null),
            Err(_) => match row.try_get::<Option<u8>, usize>(ordinal) {
                Ok(v) => v.map(Value::U8).unwrap_or(Value::Null),
                Err(_) => Value::Null,
            },
        },
        ColType::I16 => match row.try_get::<Option<i16>, usize>(ordinal) {
            Ok(v) => v.map(Value::I16).unwrap_or(Value::Null),
            Err(_) => match row.try_get::<Option<u16>, usize>(ordinal) {
                Ok(v) => v.map(Value::U16).unwrap_or(Value::Null),
                Err(_) => Value::Null,
            },
        },
        ColType::I32 => match row.try_get::<Option<i32>, usize>(ordinal) {
            Ok(v) => v.map(Value::I32).unwrap_or(Value::Null),
            Err(_) => match row.try_get::<Option<u32>, usize>(ordinal) {
                Ok(v) => v.map(Value::U32).unwrap_or(Value::Null),
                Err(_) => Value::Null,
            },
        },
        ColType::I64 => match row.try_get::<Option<i64>, usize>(ordinal) {
            Ok(v) => v.map(Value::I64).unwrap_or(Value::Null),
            Err(_) => match row.try_get::<Option<u64>, usize>(ordinal) {
                Ok(v) => v.map(Value::U64).unwrap_or(Value::Null),
                Err(_) => Value::Null,
            },
        },
        ColType::U8 => match row.try_get::<Option<u8>, usize>(ordinal) {
            Ok(v) => v.map(Value::U8).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::U16 => match row.try_get::<Option<u16>, usize>(ordinal) {
            Ok(v) => v.map(Value::U16).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::U32 => match row.try_get::<Option<u32>, usize>(ordinal) {
            Ok(v) => v.map(Value::U32).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::U64 => match row.try_get::<Option<u64>, usize>(ordinal) {
            Ok(v) => v.map(Value::U64).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::F32 => match row.try_get::<Option<f32>, usize>(ordinal) {
            Ok(v) => v.map(Value::F32).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::F64 => match row.try_get::<Option<f64>, usize>(ordinal) {
            Ok(v) => v.map(Value::F64).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        // DECIMAL/NUMERIC 使用 rust_decimal 解码,以字符串形式保留精度
        ColType::Decimal => match row.try_get::<Option<rust_decimal::Decimal>, usize>(ordinal) {
            Ok(Some(v)) => Value::Decimal(v.to_string()),
            Ok(None) => Value::Null,
            Err(_) => match row.try_get::<Option<String>, usize>(ordinal) {
                Ok(v) => v.map(Value::String).unwrap_or(Value::Null),
                Err(_) => Value::Null,
            },
        },
        ColType::String => match row.try_get::<Option<String>, usize>(ordinal) {
            Ok(v) => v.map(Value::String).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::Bytes => match row.try_get::<Option<Vec<u8>>, usize>(ordinal) {
            Ok(v) => v.map(Value::Bytes).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        // DATE/DATETIME/TIME/JSON/UUID 在 MySQL 中通常以字符串解码
        ColType::Date | ColType::DateTime | ColType::Time | ColType::Json | ColType::Uuid => {
            match row.try_get::<Option<String>, usize>(ordinal) {
                Ok(v) => v.map(Value::String).unwrap_or(Value::Null),
                Err(_) => Value::Null,
            }
        }
        ColType::Unknown => {
            // 未知类型回退:i64 → f64 → bool → String
            if let Ok(v) = row.try_get::<Option<i64>, usize>(ordinal) {
                return v.map(Value::I64).unwrap_or(Value::Null);
            }
            if let Ok(v) = row.try_get::<Option<f64>, usize>(ordinal) {
                return v.map(Value::F64).unwrap_or(Value::Null);
            }
            if let Ok(v) = row.try_get::<Option<bool>, usize>(ordinal) {
                return v.map(Value::Bool).unwrap_or(Value::Null);
            }
            if let Ok(v) = row.try_get::<Option<String>, usize>(ordinal) {
                return v.map(Value::String).unwrap_or(Value::Null);
            }
            Value::Null
        }
        // ColType 标记为 #[non_exhaustive],未来新增变体按 Unknown 处理
        _ => Value::Null,
    }
}

pub struct MySqlPoolHandle {
    pool: sqlx::MySqlPool,
}

impl MySqlPoolHandle {
    pub async fn connect(url: &str) -> Result<Self, DbError> {
        let pool = sqlx::pool::PoolOptions::<sqlx::MySql>::new()
            .max_connections(10)
            .acquire_timeout(std::time::Duration::from_secs(30))
            .idle_timeout(Some(std::time::Duration::from_secs(600)))
            .max_lifetime(Some(std::time::Duration::from_secs(1800)))
            .connect(url)
            .await
            .map_err(map_sqlx_error)?;
        Ok(Self { pool })
    }

    pub fn from_pool(pool: sqlx::MySqlPool) -> Self {
        Self { pool }
    }

    pub fn pool(&self) -> &sqlx::MySqlPool {
        &self.pool
    }
}

pub struct SqlxMySqlConnectionFactory {
    pool: Arc<MySqlPoolHandle>,
}

impl SqlxMySqlConnectionFactory {
    pub fn new(pool: Arc<MySqlPoolHandle>) -> Self {
        Self { pool }
    }
}

#[async_trait]
impl ConnectionFactory for SqlxMySqlConnectionFactory {
    async fn create(&self) -> Result<Box<dyn Connection>, DbError> {
        let conn = self.pool.pool.acquire().await.map_err(map_sqlx_error)?;
        Ok(Box::new(SqlxMySqlConnection {
            conn: Some(conn),
            connected: true,
            in_transaction: false,
        }))
    }
}

pub struct SqlxMySqlConnection {
    conn: Option<sqlx::pool::PoolConnection<sqlx::MySql>>,
    connected: bool,
    in_transaction: bool,
}

impl Connection for SqlxMySqlConnection {
    fn execute<'a>(
        &'a mut self,
        sql: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<u64, DbError>> + Send + 'a>> {
        Box::pin(async move {
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            // sqlx 0.9: PoolConnection 不再实现 Executor,需通过 DerefMut 解引用到内部连接
            // sqlx 0.9: SqlSafeStr 只对 &'static str 直接实现,非 'static 的 &str 需用 AssertSqlSafe 包装
            let result = if needs_raw_sql(sql) {
                (&mut *pool_conn)
                    .execute(sqlx::raw_sql(sqlx::AssertSqlSafe(sql)))
                    .await
            } else {
                (&mut *pool_conn).execute(sqlx::AssertSqlSafe(sql)).await
            };
            self.conn = Some(pool_conn);

            match result {
                Ok(r) => Ok(r.rows_affected()),
                Err(e) => {
                    let db_err = map_sqlx_error(e);
                    if matches!(db_err, DbError::ConnectionError(_) | DbError::IoError(_)) {
                        self.connected = false;
                    }
                    Err(db_err)
                }
            }
        })
    }

    fn query<'a>(
        &'a mut self,
        sql: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<HashMap<String, Value>>, DbError>> + Send + 'a>>
    {
        Box::pin(async move {
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            // sqlx 0.9: PoolConnection 不再实现 Executor,需通过 DerefMut 解引用到内部连接
            // sqlx 0.9: SqlSafeStr 只对 &'static str 直接实现,非 'static 的 &str 需用 AssertSqlSafe 包装
            let rows_result = (&mut *pool_conn).fetch_all(sqlx::AssertSqlSafe(sql)).await;
            self.conn = Some(pool_conn);

            let rows = rows_result.map_err(map_sqlx_error)?;
            if rows.is_empty() {
                return Ok(Vec::new());
            }
            // 预解析列类型(只在第一行解析,后续行复用,避免每行字符串 match)
            // MySQL 专用解析:覆盖 MySQL 协议特有类型名(NEWDECIMAL/YEAR/ENUM/SET 等)
            let col_types: Vec<ColType> = rows[0]
                .columns()
                .iter()
                .map(|col| ColType::parse_mysql(col.type_info().name()))
                .collect();
            let mut result = Vec::with_capacity(rows.len());
            for row in &rows {
                let mut record = HashMap::with_capacity(col_types.len());
                for (i, col) in row.columns().iter().enumerate() {
                    let name = col.name().to_string();
                    let value = row_to_value_with_coltype_mysql(row, i, col_types[i]);
                    record.insert(name, value);
                }
                result.push(record);
            }
            Ok(result)
        })
    }

    fn begin_transaction<'a>(
        &'a mut self,
    ) -> Pin<Box<dyn Future<Output = Result<(), DbError>> + Send + 'a>> {
        Box::pin(async move {
            if self.in_transaction {
                return Err(DbError::Internal("transaction already started".to_string()));
            }
            self.execute("BEGIN").await?;
            self.in_transaction = true;
            Ok(())
        })
    }

    fn commit<'a>(&'a mut self) -> Pin<Box<dyn Future<Output = Result<(), DbError>> + Send + 'a>> {
        Box::pin(async move {
            if self.in_transaction {
                self.execute("COMMIT").await?;
                self.in_transaction = false;
            }
            Ok(())
        })
    }

    fn rollback<'a>(
        &'a mut self,
    ) -> Pin<Box<dyn Future<Output = Result<(), DbError>> + Send + 'a>> {
        Box::pin(async move {
            if self.in_transaction {
                let result = self.execute("ROLLBACK").await;
                self.in_transaction = false;
                result.map(|_| ())
            } else {
                Ok(())
            }
        })
    }

    fn is_connected(&self) -> bool {
        self.connected
    }

    fn ping<'a>(&'a mut self) -> Pin<Box<dyn Future<Output = bool> + Send + 'a>> {
        Box::pin(async move {
            match self.execute("SELECT 1").await {
                Ok(_) => true,
                Err(_) => {
                    self.connected = false;
                    false
                }
            }
        })
    }

    fn close<'a>(&'a mut self) -> Pin<Box<dyn Future<Output = Result<(), DbError>> + Send + 'a>> {
        Box::pin(async move {
            if let Some(conn) = self.conn.take() {
                drop(conn);
            }
            self.connected = false;
            self.in_transaction = false;
            Ok(())
        })
    }

    /// MySQL 参数绑定执行(INSERT/UPDATE/DELETE)
    ///
    /// 使用 sqlx prepared statement 绑定参数。MySQL 协议原生支持 `?` 占位符。
    /// 对 `Value::Bool`/`I8`..=`I64`/`U8`..=`U64`/`F32`/`F64`/`String`/`Bytes` 直接 bind;
    /// 其他类型回退为 `to_string()` 后以 TEXT 绑定。
    fn execute_with_params<'a>(
        &'a mut self,
        sql: &'a str,
        params: &'a [Value],
    ) -> Pin<Box<dyn Future<Output = Result<u64, DbError>> + Send + 'a>> {
        Box::pin(async move {
            if needs_raw_sql(sql) || params.is_empty() {
                return self.execute(sql).await;
            }
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            let mut q = sqlx::query(sqlx::AssertSqlSafe(sql));
            for v in params {
                q = match v {
                    Value::Null => q.bind(None::<i64>),
                    Value::Bool(b) => q.bind(*b),
                    Value::I8(n) => q.bind(*n),
                    Value::I16(n) => q.bind(*n),
                    Value::I32(n) => q.bind(*n),
                    Value::I64(n) => q.bind(*n),
                    Value::U8(n) => q.bind(*n),
                    Value::U16(n) => q.bind(*n),
                    Value::U32(n) => q.bind(*n),
                    Value::U64(n) => q.bind(*n as i64),
                    Value::F32(f) => q.bind(*f),
                    Value::F64(f) => q.bind(*f),
                    Value::String(s) => q.bind(s.as_str()),
                    Value::Decimal(s) => q.bind(s.as_str()),
                    Value::Bytes(b) => q.bind(b.as_slice()),
                    other => q.bind(other.to_string()),
                };
            }
            let result = q.execute(&mut *pool_conn).await;
            self.conn = Some(pool_conn);
            match result {
                Ok(r) => Ok(r.rows_affected()),
                Err(e) => {
                    let db_err = map_sqlx_error(e);
                    if matches!(db_err, DbError::ConnectionError(_) | DbError::IoError(_)) {
                        self.connected = false;
                    }
                    Err(db_err)
                }
            }
        })
    }

    /// MySQL 参数绑定查询(SELECT,HashMap 映射)
    fn query_with_params<'a>(
        &'a mut self,
        sql: &'a str,
        params: &'a [Value],
    ) -> Pin<Box<dyn Future<Output = Result<QueryRows, DbError>> + Send + 'a>> {
        Box::pin(async move {
            if params.is_empty() {
                return self.query(sql).await;
            }
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            let mut q = sqlx::query(sqlx::AssertSqlSafe(sql));
            for v in params {
                q = match v {
                    Value::Null => q.bind(None::<i64>),
                    Value::Bool(b) => q.bind(*b),
                    Value::I8(n) => q.bind(*n),
                    Value::I16(n) => q.bind(*n),
                    Value::I32(n) => q.bind(*n),
                    Value::I64(n) => q.bind(*n),
                    Value::U8(n) => q.bind(*n),
                    Value::U16(n) => q.bind(*n),
                    Value::U32(n) => q.bind(*n),
                    Value::U64(n) => q.bind(*n as i64),
                    Value::F32(f) => q.bind(*f),
                    Value::F64(f) => q.bind(*f),
                    Value::String(s) => q.bind(s.as_str()),
                    Value::Decimal(s) => q.bind(s.as_str()),
                    Value::Bytes(b) => q.bind(b.as_slice()),
                    other => q.bind(other.to_string()),
                };
            }
            let rows_result = q.fetch_all(&mut *pool_conn).await;
            self.conn = Some(pool_conn);
            let rows = rows_result.map_err(map_sqlx_error)?;
            let mut result = Vec::with_capacity(rows.len());
            for row in rows {
                // #13 修复:预分配 HashMap 容量,避免逐列 insert 时 rehash/growth
                let columns = row.columns();
                let mut record = HashMap::with_capacity(columns.len());
                for col in columns {
                    let name = col.name().to_string();
                    let ordinal = col.ordinal();
                    let value = row_to_value_mysql(&row, ordinal);
                    record.insert(name, value);
                }
                result.push(record);
            }
            Ok(result)
        })
    }

    /// MySQL 位置式查询(SELECT,无参数)
    ///
    /// 绕过 HashMap 行映射,返回 `(列名, 按列序号的值矩阵)`。适用于 SELECT ALL 大结果集。
    fn query_values<'a>(
        &'a mut self,
        sql: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<QueryValues, DbError>> + Send + 'a>> {
        Box::pin(async move {
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            let rows_result = (&mut *pool_conn).fetch_all(sqlx::AssertSqlSafe(sql)).await;
            self.conn = Some(pool_conn);
            let rows = rows_result.map_err(map_sqlx_error)?;
            if rows.is_empty() {
                return Ok((Vec::new(), Vec::new()));
            }
            let cols = rows[0].columns();
            let mut col_names: Vec<String> = Vec::with_capacity(cols.len());
            let mut col_types: Vec<ColType> = Vec::with_capacity(cols.len());
            for col in cols {
                col_names.push(col.name().to_string());
                col_types.push(ColType::parse_mysql(col.type_info().name()));
            }
            let mut result_rows: Vec<Vec<Value>> = Vec::with_capacity(rows.len());
            for row in &rows {
                let mut row_values: Vec<Value> = Vec::with_capacity(col_names.len());
                for (idx, _) in col_names.iter().enumerate() {
                    row_values.push(row_to_value_with_coltype_mysql(row, idx, col_types[idx]));
                }
                result_rows.push(row_values);
            }
            Ok((col_names, result_rows))
        })
    }

    /// MySQL 参数绑定位置式查询(SELECT)
    fn query_values_with_params<'a>(
        &'a mut self,
        sql: &'a str,
        params: &'a [Value],
    ) -> Pin<Box<dyn Future<Output = Result<QueryValues, DbError>> + Send + 'a>> {
        Box::pin(async move {
            if params.is_empty() {
                return self.query_values(sql).await;
            }
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            let mut q = sqlx::query(sqlx::AssertSqlSafe(sql));
            for v in params {
                q = match v {
                    Value::Null => q.bind(None::<i64>),
                    Value::Bool(b) => q.bind(*b),
                    Value::I8(n) => q.bind(*n),
                    Value::I16(n) => q.bind(*n),
                    Value::I32(n) => q.bind(*n),
                    Value::I64(n) => q.bind(*n),
                    Value::U8(n) => q.bind(*n),
                    Value::U16(n) => q.bind(*n),
                    Value::U32(n) => q.bind(*n),
                    Value::U64(n) => q.bind(*n as i64),
                    Value::F32(f) => q.bind(*f),
                    Value::F64(f) => q.bind(*f),
                    Value::String(s) => q.bind(s.as_str()),
                    Value::Decimal(s) => q.bind(s.as_str()),
                    Value::Bytes(b) => q.bind(b.as_slice()),
                    other => q.bind(other.to_string()),
                };
            }
            let rows_result = q.fetch_all(&mut *pool_conn).await;
            self.conn = Some(pool_conn);
            let rows = rows_result.map_err(map_sqlx_error)?;
            if rows.is_empty() {
                return Ok((Vec::new(), Vec::new()));
            }
            let cols = rows[0].columns();
            let mut col_names: Vec<String> = Vec::with_capacity(cols.len());
            let mut col_types: Vec<ColType> = Vec::with_capacity(cols.len());
            for col in cols {
                col_names.push(col.name().to_string());
                col_types.push(ColType::parse_mysql(col.type_info().name()));
            }
            let mut result_rows: Vec<Vec<Value>> = Vec::with_capacity(rows.len());
            for row in &rows {
                let mut row_values: Vec<Value> = Vec::with_capacity(col_names.len());
                for (idx, _) in col_names.iter().enumerate() {
                    row_values.push(row_to_value_with_coltype_mysql(row, idx, col_types[idx]));
                }
                result_rows.push(row_values);
            }
            Ok((col_names, result_rows))
        })
    }

    /// MySQL 流式查询:逐行返回结果,避免大结果集 `fetch_all` 内存峰值
    ///
    /// 使用 `sqlx::query::fetch` 获取行流,逐行映射为 `HashMap<String, Value>`。
    /// 流正常消费完毕后连接归还 `self.conn`;若提前 drop 流,连接通过
    /// `PoolConnection::drop` 归还到 sqlx 池,但 `self.conn` 变为 `None`。
    fn query_stream<'a>(
        &'a mut self,
        sql: &'a str,
    ) -> Pin<Box<dyn futures::Stream<Item = Result<HashMap<String, Value>, DbError>> + Send + 'a>>
    {
        Box::pin(async_stream::try_stream! {
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            let mut row_stream = sqlx::query(sqlx::AssertSqlSafe(sql)).fetch(&mut *pool_conn);
            let mut col_types: Vec<ColType> = Vec::new();
            let mut col_names: Vec<String> = Vec::new();
            let mut first_row = true;
            while let Some(row_result) = row_stream.next().await {
                let row = row_result.map_err(map_sqlx_error)?;
                if first_row {
                    for col in row.columns() {
                        col_names.push(col.name().to_string());
                        col_types.push(ColType::parse_mysql(col.type_info().name()));
                    }
                    first_row = false;
                }
                let mut record = HashMap::with_capacity(col_names.len());
                for (i, name) in col_names.iter().enumerate() {
                    let value = row_to_value_with_coltype_mysql(&row, i, col_types[i]);
                    record.insert(name.clone(), value);
                }
                yield record;
            }
            // 显式释放 row_stream 对 pool_conn 的可变借用,否则借用检查器
            // 无法证明 row_stream 在移动 pool_conn 前已被销毁(E0505)
            drop(row_stream);
            self.conn = Some(pool_conn);
        })
    }
}

impl Drop for SqlxMySqlConnection {
    fn drop(&mut self) {
        if let Some(conn) = self.conn.take() {
            drop(conn);
        }
    }
}

/// MySQL 批量导入(多行 INSERT,作为 LOAD DATA LOCAL INFILE 的安全替代)
///
/// 构建多行 INSERT 语句:`INSERT INTO t (c1, c2) VALUES (?, ?), (?, ?), ...`
/// 使用参数绑定避免 SQL 注入。MySQL 原生支持 `?` 占位符。
/// 当数据量极大时建议分批调用(每批 1000~10000 行),避免 SQL 过长或超出
/// `max_allowed_packet` 限制。
pub async fn mysql_bulk_insert(
    conn: &mut SqlxMySqlConnection,
    table: &str,
    columns: &[&str],
    rows: &[Vec<Value>],
) -> Result<u64, DbError> {
    if rows.is_empty() {
        return Ok(0);
    }
    let col_list = columns.join(", ");
    let cols_per_row = columns.len();
    // MySQL 占位符 ? 每列一个,跨行复用相同模式
    let row_placeholder = format!("({})", vec!["?"; cols_per_row].join(", "));
    let placeholders = vec![row_placeholder; rows.len()].join(", ");
    let sql = format!(
        "INSERT INTO {} ({}) VALUES {}",
        table, col_list, placeholders
    );
    // 展平所有行的值为单一参数数组
    let mut params: Vec<Value> = Vec::with_capacity(rows.len() * cols_per_row);
    for row in rows {
        for v in row {
            params.push(v.clone());
        }
    }
    conn.execute_with_params(&sql, &params).await
}

// ===================== PostgreSQL 适配器 =====================

// 注:sqlx 0.9 起 Executor trait 要求 'static lifetime,
// 原先的 execute_pg_boxed / query_pg_boxed 已内联到调用点。

fn row_to_value_pg(row: &sqlx::postgres::PgRow, ordinal: usize) -> Value {
    use sqlx::TypeInfo;
    let type_name = row.columns()[ordinal].type_info().name();
    match type_name {
        "BOOL" => match row.try_get::<Option<bool>, usize>(ordinal) {
            Ok(v) => v.map(Value::Bool).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        "INT2" => match row.try_get::<Option<i16>, usize>(ordinal) {
            Ok(v) => v.map(Value::I16).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        "INT4" | "OID" => match row.try_get::<Option<i32>, usize>(ordinal) {
            Ok(v) => v.map(Value::I32).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        "INT8" => match row.try_get::<Option<i64>, usize>(ordinal) {
            Ok(v) => v.map(Value::I64).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        "FLOAT4" => match row.try_get::<Option<f32>, usize>(ordinal) {
            Ok(v) => v.map(Value::F32).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        "FLOAT8" => match row.try_get::<Option<f64>, usize>(ordinal) {
            Ok(v) => v.map(Value::F64).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        "TEXT" | "VARCHAR" | "CHAR" | "NAME" => match row.try_get::<Option<String>, usize>(ordinal)
        {
            Ok(v) => v.map(Value::String).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        "BYTEA" => match row.try_get::<Option<Vec<u8>>, usize>(ordinal) {
            Ok(v) => v.map(Value::Bytes).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        "NUMERIC" => match row.try_get::<Option<rust_decimal::Decimal>, usize>(ordinal) {
            Ok(Some(v)) => Value::Decimal(v.to_string()),
            Ok(None) => Value::Null,
            Err(_) => match row.try_get::<Option<String>, usize>(ordinal) {
                Ok(v) => v.map(Value::String).unwrap_or(Value::Null),
                Err(_) => Value::Null,
            },
        },
        // UUID:使用 sqlx::types::Uuid(16 字节)解码,避免 36 字符字符串的内存浪费
        "UUID" => match row.try_get::<Option<sqlx::types::Uuid>, usize>(ordinal) {
            Ok(v) => v
                .map(|uuid| Value::String(uuid.to_string()))
                .unwrap_or(Value::Null),
            Err(_) => match row.try_get::<Option<String>, usize>(ordinal) {
                Ok(v) => v.map(Value::String).unwrap_or(Value::Null),
                Err(_) => Value::Null,
            },
        },
        _ => {
            // 未知类型回退
            if let Ok(v) = row.try_get::<Option<i64>, usize>(ordinal) {
                return v.map(Value::I64).unwrap_or(Value::Null);
            }
            if let Ok(v) = row.try_get::<Option<f64>, usize>(ordinal) {
                return v.map(Value::F64).unwrap_or(Value::Null);
            }
            if let Ok(v) = row.try_get::<Option<bool>, usize>(ordinal) {
                return v.map(Value::Bool).unwrap_or(Value::Null);
            }
            if let Ok(v) = row.try_get::<Option<String>, usize>(ordinal) {
                return v.map(Value::String).unwrap_or(Value::Null);
            }
            Value::Null
        }
    }
}

/// PostgreSQL: 使用预解析的 ColType 进行类型分派(避免每行字符串 match)
///
/// 与 [`row_to_value_pg`] 的区别:调用方预先通过 [`ColType::parse_postgres`] 解析列类型,
/// 后续行直接用枚举分派(编译器优化为跳转表),避免每行每列的字符串比较。
///
/// **注意**:必须使用 `parse_postgres` 而非通用 `from_type_name`:PostgreSQL 使用
/// PG 内部类型名(INT4/INT8/FLOAT8/BPCHAR/JSONB/TIMESTAMPTZ 等),通用映射无法识别。
fn row_to_value_with_coltype_pg(
    row: &sqlx::postgres::PgRow,
    ordinal: usize,
    col_type: ColType,
) -> Value {
    match col_type {
        ColType::Bool => match row.try_get::<Option<bool>, usize>(ordinal) {
            Ok(v) => v.map(Value::Bool).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::I8 => match row.try_get::<Option<i8>, usize>(ordinal) {
            Ok(v) => v.map(Value::I8).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::I16 => match row.try_get::<Option<i16>, usize>(ordinal) {
            Ok(v) => v.map(Value::I16).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        // PostgreSQL OID 在 parse_postgres 中归为 I32
        ColType::I32 => match row.try_get::<Option<i32>, usize>(ordinal) {
            Ok(v) => v.map(Value::I32).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::I64 => match row.try_get::<Option<i64>, usize>(ordinal) {
            Ok(v) => v.map(Value::I64).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        // PostgreSQL 无原生无符号类型(u8/u16/u32):
        // - ColType::U8/U16/U32 仅在 parse_postgres 误判时出现(PG 无 UNSIGNED 关键字)
        // - 退化为最小可容纳的有符号类型:U8→i16、U16→i32、U32→i64
        // - 数值正确性保持,仅在 Value 枚举上为有符号变体(与 sqlx Type<Postgres> 实现一致)
        ColType::U8 => match row.try_get::<Option<i16>, usize>(ordinal) {
            Ok(v) => v.map(Value::I16).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::U16 => match row.try_get::<Option<i32>, usize>(ordinal) {
            Ok(v) => v.map(Value::I32).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::U32 => match row.try_get::<Option<i64>, usize>(ordinal) {
            Ok(v) => v.map(Value::I64).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        // PostgreSQL 无原生 U64,按 i64 解码
        ColType::U64 => match row.try_get::<Option<i64>, usize>(ordinal) {
            Ok(v) => v.map(Value::I64).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::F32 => match row.try_get::<Option<f32>, usize>(ordinal) {
            Ok(v) => v.map(Value::F32).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::F64 => match row.try_get::<Option<f64>, usize>(ordinal) {
            Ok(v) => v.map(Value::F64).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        // NUMERIC/DECIMAL/MONEY 使用 rust_decimal 解码,以字符串形式保留精度
        ColType::Decimal => match row.try_get::<Option<rust_decimal::Decimal>, usize>(ordinal) {
            Ok(Some(v)) => Value::Decimal(v.to_string()),
            Ok(None) => Value::Null,
            Err(_) => match row.try_get::<Option<String>, usize>(ordinal) {
                Ok(v) => v.map(Value::String).unwrap_or(Value::Null),
                Err(_) => Value::Null,
            },
        },
        ColType::String => match row.try_get::<Option<String>, usize>(ordinal) {
            Ok(v) => v.map(Value::String).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        ColType::Bytes => match row.try_get::<Option<Vec<u8>>, usize>(ordinal) {
            Ok(v) => v.map(Value::Bytes).unwrap_or(Value::Null),
            Err(_) => Value::Null,
        },
        // DATE/DATETIME/TIME/JSON 在 PostgreSQL 中通常以字符串解码
        ColType::Date | ColType::DateTime | ColType::Time | ColType::Json => {
            match row.try_get::<Option<String>, usize>(ordinal) {
                Ok(v) => v.map(Value::String).unwrap_or(Value::Null),
                Err(_) => Value::Null,
            }
        }
        // UUID:使用 sqlx::types::Uuid(16 字节)解码,避免 36 字符字符串的内存浪费
        ColType::Uuid => match row.try_get::<Option<sqlx::types::Uuid>, usize>(ordinal) {
            Ok(v) => v
                .map(|uuid| Value::String(uuid.to_string()))
                .unwrap_or(Value::Null),
            Err(_) => match row.try_get::<Option<String>, usize>(ordinal) {
                Ok(v) => v.map(Value::String).unwrap_or(Value::Null),
                Err(_) => Value::Null,
            },
        },
        ColType::Unknown => {
            // 未知类型回退:i64 → f64 → bool → String
            if let Ok(v) = row.try_get::<Option<i64>, usize>(ordinal) {
                return v.map(Value::I64).unwrap_or(Value::Null);
            }
            if let Ok(v) = row.try_get::<Option<f64>, usize>(ordinal) {
                return v.map(Value::F64).unwrap_or(Value::Null);
            }
            if let Ok(v) = row.try_get::<Option<bool>, usize>(ordinal) {
                return v.map(Value::Bool).unwrap_or(Value::Null);
            }
            if let Ok(v) = row.try_get::<Option<String>, usize>(ordinal) {
                return v.map(Value::String).unwrap_or(Value::Null);
            }
            Value::Null
        }
        // ColType 标记为 #[non_exhaustive],未来新增变体按 Unknown 处理
        _ => Value::Null,
    }
}

pub struct PgPoolHandle {
    pool: sqlx::PgPool,
}

impl PgPoolHandle {
    pub async fn connect(url: &str) -> Result<Self, DbError> {
        let pool = sqlx::pool::PoolOptions::<sqlx::Postgres>::new()
            .max_connections(10)
            .acquire_timeout(std::time::Duration::from_secs(30))
            .idle_timeout(Some(std::time::Duration::from_secs(600)))
            .max_lifetime(Some(std::time::Duration::from_secs(1800)))
            .connect(url)
            .await
            .map_err(map_sqlx_error)?;
        Ok(Self { pool })
    }

    pub fn from_pool(pool: sqlx::PgPool) -> Self {
        Self { pool }
    }

    pub fn pool(&self) -> &sqlx::PgPool {
        &self.pool
    }
}

pub struct SqlxPgConnectionFactory {
    pool: Arc<PgPoolHandle>,
}

impl SqlxPgConnectionFactory {
    pub fn new(pool: Arc<PgPoolHandle>) -> Self {
        Self { pool }
    }
}

#[async_trait]
impl ConnectionFactory for SqlxPgConnectionFactory {
    async fn create(&self) -> Result<Box<dyn Connection>, DbError> {
        let conn = self.pool.pool.acquire().await.map_err(map_sqlx_error)?;
        Ok(Box::new(SqlxPgConnection {
            conn: Some(conn),
            connected: true,
            in_transaction: false,
        }))
    }
}

pub struct SqlxPgConnection {
    conn: Option<sqlx::pool::PoolConnection<sqlx::Postgres>>,
    connected: bool,
    in_transaction: bool,
}

impl Connection for SqlxPgConnection {
    fn execute<'a>(
        &'a mut self,
        sql: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<u64, DbError>> + Send + 'a>> {
        Box::pin(async move {
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            // sqlx 0.9: PoolConnection 不再实现 Executor,需通过 DerefMut 解引用到内部连接
            // sqlx 0.9: SqlSafeStr 只对 &'static str 直接实现,非 'static 的 &str 需用 AssertSqlSafe 包装
            let result = if needs_raw_sql(sql) {
                (&mut *pool_conn)
                    .execute(sqlx::raw_sql(sqlx::AssertSqlSafe(sql)))
                    .await
            } else {
                (&mut *pool_conn).execute(sqlx::AssertSqlSafe(sql)).await
            };
            self.conn = Some(pool_conn);

            match result {
                Ok(r) => Ok(r.rows_affected()),
                Err(e) => {
                    let db_err = map_sqlx_error(e);
                    if matches!(db_err, DbError::ConnectionError(_) | DbError::IoError(_)) {
                        self.connected = false;
                    }
                    Err(db_err)
                }
            }
        })
    }

    fn query<'a>(
        &'a mut self,
        sql: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<HashMap<String, Value>>, DbError>> + Send + 'a>>
    {
        Box::pin(async move {
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            // sqlx 0.9: PoolConnection 不再实现 Executor,需通过 DerefMut 解引用到内部连接
            // sqlx 0.9: SqlSafeStr 只对 &'static str 直接实现,非 'static 的 &str 需用 AssertSqlSafe 包装
            let rows_result = (&mut *pool_conn).fetch_all(sqlx::AssertSqlSafe(sql)).await;
            self.conn = Some(pool_conn);

            let rows = rows_result.map_err(map_sqlx_error)?;
            if rows.is_empty() {
                return Ok(Vec::new());
            }
            // 预解析列类型(只在第一行解析,后续行复用,避免每行字符串 match)
            // PostgreSQL 专用解析:覆盖 PG 内部类型名(INT4/INT8/FLOAT8/BPCHAR/JSONB 等)
            let col_types: Vec<ColType> = rows[0]
                .columns()
                .iter()
                .map(|col| ColType::parse_postgres(col.type_info().name()))
                .collect();
            let mut result = Vec::with_capacity(rows.len());
            for row in &rows {
                let mut record = HashMap::with_capacity(col_types.len());
                for (i, col) in row.columns().iter().enumerate() {
                    let name = col.name().to_string();
                    let value = row_to_value_with_coltype_pg(row, i, col_types[i]);
                    record.insert(name, value);
                }
                result.push(record);
            }
            Ok(result)
        })
    }

    fn begin_transaction<'a>(
        &'a mut self,
    ) -> Pin<Box<dyn Future<Output = Result<(), DbError>> + Send + 'a>> {
        Box::pin(async move {
            if self.in_transaction {
                return Err(DbError::Internal("transaction already started".to_string()));
            }
            self.execute("BEGIN").await?;
            self.in_transaction = true;
            Ok(())
        })
    }

    fn commit<'a>(&'a mut self) -> Pin<Box<dyn Future<Output = Result<(), DbError>> + Send + 'a>> {
        Box::pin(async move {
            if self.in_transaction {
                self.execute("COMMIT").await?;
                self.in_transaction = false;
            }
            Ok(())
        })
    }

    fn rollback<'a>(
        &'a mut self,
    ) -> Pin<Box<dyn Future<Output = Result<(), DbError>> + Send + 'a>> {
        Box::pin(async move {
            if self.in_transaction {
                let result = self.execute("ROLLBACK").await;
                self.in_transaction = false;
                result.map(|_| ())
            } else {
                Ok(())
            }
        })
    }

    fn is_connected(&self) -> bool {
        self.connected
    }

    fn ping<'a>(&'a mut self) -> Pin<Box<dyn Future<Output = bool> + Send + 'a>> {
        Box::pin(async move {
            match self.execute("SELECT 1").await {
                Ok(_) => true,
                Err(_) => {
                    self.connected = false;
                    false
                }
            }
        })
    }

    fn close<'a>(&'a mut self) -> Pin<Box<dyn Future<Output = Result<(), DbError>> + Send + 'a>> {
        Box::pin(async move {
            if let Some(conn) = self.conn.take() {
                drop(conn);
            }
            self.connected = false;
            self.in_transaction = false;
            Ok(())
        })
    }

    /// PostgreSQL 参数绑定执行(INSERT/UPDATE/DELETE)
    ///
    /// 使用 sqlx prepared statement 绑定参数。PostgreSQL 协议使用 `$1, $2, ...` 占位符。
    ///
    /// # 类型映射说明
    ///
    /// PostgreSQL 不支持无符号整数类型(u8/u16/u32/u64),因此无符号 Value 绑定
    /// 时按"最小可容纳的有符号类型"转换:
    /// - `U8`  → `i16`(PostgreSQL `SMALLINT`)
    /// - `U16` → `i32`(PostgreSQL `INTEGER`)
    /// - `U32` → `i64`(PostgreSQL `BIGINT`)
    /// - `U64` → `i64`(可能截断,仅适用于 < `i64::MAX` 的值)
    ///
    /// 其他类型直接 bind;未知类型回退为 `to_string()` 后以 TEXT 绑定。
    fn execute_with_params<'a>(
        &'a mut self,
        sql: &'a str,
        params: &'a [Value],
    ) -> Pin<Box<dyn Future<Output = Result<u64, DbError>> + Send + 'a>> {
        Box::pin(async move {
            if needs_raw_sql(sql) || params.is_empty() {
                return self.execute(sql).await;
            }
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            let mut q = sqlx::query(sqlx::AssertSqlSafe(sql));
            for v in params {
                q = match v {
                    Value::Null => q.bind(None::<i64>),
                    Value::Bool(b) => q.bind(*b),
                    Value::I8(n) => q.bind(*n),
                    Value::I16(n) => q.bind(*n),
                    Value::I32(n) => q.bind(*n),
                    Value::I64(n) => q.bind(*n),
                    // PostgreSQL 无 u8/u16/u32/u64:按最小可容纳有符号类型转换
                    Value::U8(n) => q.bind(*n as i16),
                    Value::U16(n) => q.bind(*n as i32),
                    Value::U32(n) => q.bind(*n as i64),
                    Value::U64(n) => q.bind(*n as i64),
                    Value::F32(f) => q.bind(*f),
                    Value::F64(f) => q.bind(*f),
                    Value::String(s) => q.bind(s.as_str()),
                    Value::Decimal(s) => q.bind(s.as_str()),
                    Value::Bytes(b) => q.bind(b.as_slice()),
                    other => q.bind(other.to_string()),
                };
            }
            let result = q.execute(&mut *pool_conn).await;
            self.conn = Some(pool_conn);
            match result {
                Ok(r) => Ok(r.rows_affected()),
                Err(e) => {
                    let db_err = map_sqlx_error(e);
                    if matches!(db_err, DbError::ConnectionError(_) | DbError::IoError(_)) {
                        self.connected = false;
                    }
                    Err(db_err)
                }
            }
        })
    }

    /// PostgreSQL 参数绑定查询(SELECT,HashMap 映射)
    ///
    /// 类型映射规则与 [`Self::execute_with_params`] 相同。
    fn query_with_params<'a>(
        &'a mut self,
        sql: &'a str,
        params: &'a [Value],
    ) -> Pin<Box<dyn Future<Output = Result<QueryRows, DbError>> + Send + 'a>> {
        Box::pin(async move {
            if params.is_empty() {
                return self.query(sql).await;
            }
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            let mut q = sqlx::query(sqlx::AssertSqlSafe(sql));
            for v in params {
                q = match v {
                    Value::Null => q.bind(None::<i64>),
                    Value::Bool(b) => q.bind(*b),
                    Value::I8(n) => q.bind(*n),
                    Value::I16(n) => q.bind(*n),
                    Value::I32(n) => q.bind(*n),
                    Value::I64(n) => q.bind(*n),
                    Value::U8(n) => q.bind(*n as i16),
                    Value::U16(n) => q.bind(*n as i32),
                    Value::U32(n) => q.bind(*n as i64),
                    Value::U64(n) => q.bind(*n as i64),
                    Value::F32(f) => q.bind(*f),
                    Value::F64(f) => q.bind(*f),
                    Value::String(s) => q.bind(s.as_str()),
                    Value::Decimal(s) => q.bind(s.as_str()),
                    Value::Bytes(b) => q.bind(b.as_slice()),
                    other => q.bind(other.to_string()),
                };
            }
            let rows_result = q.fetch_all(&mut *pool_conn).await;
            self.conn = Some(pool_conn);
            let rows = rows_result.map_err(map_sqlx_error)?;
            if rows.is_empty() {
                return Ok(Vec::new());
            }
            // 预解析列类型(只在第一行解析,后续行复用,避免每行字符串 match)
            let col_types: Vec<ColType> = rows[0]
                .columns()
                .iter()
                .map(|col| ColType::parse_postgres(col.type_info().name()))
                .collect();
            let mut result = Vec::with_capacity(rows.len());
            for row in &rows {
                let mut record = HashMap::with_capacity(col_types.len());
                for (i, col) in row.columns().iter().enumerate() {
                    let name = col.name().to_string();
                    let value = row_to_value_with_coltype_pg(row, i, col_types[i]);
                    record.insert(name, value);
                }
                result.push(record);
            }
            Ok(result)
        })
    }

    /// PostgreSQL 位置式查询(SELECT,无参数)
    ///
    /// 绕过 HashMap 行映射,返回 `(列名, 按列序号的值矩阵)`。适用于 SELECT ALL 大结果集。
    fn query_values<'a>(
        &'a mut self,
        sql: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<QueryValues, DbError>> + Send + 'a>> {
        Box::pin(async move {
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            let rows_result = (&mut *pool_conn).fetch_all(sqlx::AssertSqlSafe(sql)).await;
            self.conn = Some(pool_conn);
            let rows = rows_result.map_err(map_sqlx_error)?;
            if rows.is_empty() {
                return Ok((Vec::new(), Vec::new()));
            }
            let cols = rows[0].columns();
            let mut col_names: Vec<String> = Vec::with_capacity(cols.len());
            for col in cols {
                col_names.push(col.name().to_string());
            }
            let mut result_rows: Vec<Vec<Value>> = Vec::with_capacity(rows.len());
            for row in rows {
                let mut row_values: Vec<Value> = Vec::with_capacity(col_names.len());
                for (idx, _) in col_names.iter().enumerate() {
                    let ordinal = row.columns()[idx].ordinal();
                    row_values.push(row_to_value_pg(&row, ordinal));
                }
                result_rows.push(row_values);
            }
            Ok((col_names, result_rows))
        })
    }

    /// PostgreSQL 参数绑定位置式查询(SELECT)
    ///
    /// 类型映射规则与 [`Self::execute_with_params`] 相同。
    fn query_values_with_params<'a>(
        &'a mut self,
        sql: &'a str,
        params: &'a [Value],
    ) -> Pin<Box<dyn Future<Output = Result<QueryValues, DbError>> + Send + 'a>> {
        Box::pin(async move {
            if params.is_empty() {
                return self.query_values(sql).await;
            }
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            let mut q = sqlx::query(sqlx::AssertSqlSafe(sql));
            for v in params {
                q = match v {
                    Value::Null => q.bind(None::<i64>),
                    Value::Bool(b) => q.bind(*b),
                    Value::I8(n) => q.bind(*n),
                    Value::I16(n) => q.bind(*n),
                    Value::I32(n) => q.bind(*n),
                    Value::I64(n) => q.bind(*n),
                    Value::U8(n) => q.bind(*n as i16),
                    Value::U16(n) => q.bind(*n as i32),
                    Value::U32(n) => q.bind(*n as i64),
                    Value::U64(n) => q.bind(*n as i64),
                    Value::F32(f) => q.bind(*f),
                    Value::F64(f) => q.bind(*f),
                    Value::String(s) => q.bind(s.as_str()),
                    Value::Decimal(s) => q.bind(s.as_str()),
                    Value::Bytes(b) => q.bind(b.as_slice()),
                    other => q.bind(other.to_string()),
                };
            }
            let rows_result = q.fetch_all(&mut *pool_conn).await;
            self.conn = Some(pool_conn);
            let rows = rows_result.map_err(map_sqlx_error)?;
            if rows.is_empty() {
                return Ok((Vec::new(), Vec::new()));
            }
            let cols = rows[0].columns();
            let mut col_names: Vec<String> = Vec::with_capacity(cols.len());
            for col in cols {
                col_names.push(col.name().to_string());
            }
            let mut result_rows: Vec<Vec<Value>> = Vec::with_capacity(rows.len());
            for row in rows {
                let mut row_values: Vec<Value> = Vec::with_capacity(col_names.len());
                for (idx, _) in col_names.iter().enumerate() {
                    let ordinal = row.columns()[idx].ordinal();
                    row_values.push(row_to_value_pg(&row, ordinal));
                }
                result_rows.push(row_values);
            }
            Ok((col_names, result_rows))
        })
    }

    /// PostgreSQL 流式查询:逐行返回结果,避免大结果集 `fetch_all` 内存峰值
    ///
    /// 使用 `sqlx::query::fetch` 获取行流,逐行映射为 `HashMap<String, Value>`。
    /// 流正常消费完毕后连接归还 `self.conn`;若提前 drop 流,连接通过
    /// `PoolConnection::drop` 归还到 sqlx 池,但 `self.conn` 变为 `None`。
    ///
    /// 注意:PostgreSQL 的 `fetch` 返回 `Pin<Box<dyn Stream<...>>>`(boxed trait object),
    /// 其析构函数可能持有 `pool_conn` 的借用,导致无法直接 `self.conn = Some(pool_conn)`。
    /// 通过显式 `drop(row_stream)` 提前结束借用,再归还连接。
    fn query_stream<'a>(
        &'a mut self,
        sql: &'a str,
    ) -> Pin<Box<dyn futures::Stream<Item = Result<HashMap<String, Value>, DbError>> + Send + 'a>>
    {
        Box::pin(async_stream::try_stream! {
            let mut pool_conn = self
                .conn
                .take()
                .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
            let mut row_stream = sqlx::query(sqlx::AssertSqlSafe(sql)).fetch(&mut *pool_conn);
            // 流式查询无法预解析第一行列类型(流首行未知),使用每行 columns() 长度预分配 HashMap
            // 仍然使用 row_to_value_pg(按列类型字符串 match)以保证正确性
            while let Some(row_result) = row_stream.next().await {
                let row = row_result.map_err(map_sqlx_error)?;
                let cols = row.columns();
                let mut record = HashMap::with_capacity(cols.len());
                for (i, col) in cols.iter().enumerate() {
                    let name = col.name().to_string();
                    // 流式场景下每行都解析 ColType 反而增加开销,直接使用 row_to_value_pg
                    let value = row_to_value_pg(&row, i);
                    record.insert(name, value);
                }
                yield record;
            }
            // 显式 drop row_stream 以释放对 pool_conn 的借用
            // PostgreSQL 的 fetch 流是 boxed trait object,析构函数可能持有借用
            drop(row_stream);
            self.conn = Some(pool_conn);
        })
    }
}

impl Drop for SqlxPgConnection {
    fn drop(&mut self) {
        if let Some(conn) = self.conn.take() {
            drop(conn);
        }
    }
}

// ===================== PostgreSQL 扩展功能 =====================

/// PostgreSQL 扩展功能 trait
///
/// 提供 PostgreSQL 特有的 LISTEN/NOTIFY 通道通信与 COPY FROM STDIN 批量导入功能。
/// 这些功能在其他数据库(MySQL/SQLite)中没有对应实现,因此单独定义为扩展 trait,
/// 仅由 [`SqlxPgConnection`] 实现。
///
/// # LISTEN/NOTIFY
///
/// PostgreSQL 的轻量级进程间通信机制:
/// - `LISTEN channel`:订阅通道
/// - `NOTIFY channel, payload`:向通道发送通知
///
/// 接收通知需配合 `PgListener` 或轮询 `pg_notification` 系列函数。
///
/// # COPY FROM STDIN
///
/// PostgreSQL 的高性能批量导入协议,比逐行 INSERT 快 10~100 倍。
/// 数据通过专用协议流式传输,绕过 SQL 解析器。
#[async_trait]
pub trait PgExtensions: Send + Sync {
    /// LISTEN 通道:订阅指定通道的通知
    ///
    /// # 参数
    ///
    /// - `channel`: 通道名(仅允许字母、数字、下划线,防止 SQL 注入)
    ///
    /// # 错误
    ///
    /// - 通道名包含非法字符时返回 `DbError::Internal`
    /// - 连接已关闭时返回 `DbError::Internal`
    async fn listen(&mut self, channel: &str) -> Result<(), DbError>;

    /// NOTIFY 通道:向指定通道发送通知
    ///
    /// # 参数
    ///
    /// - `channel`: 通道名(仅允许字母、数字、下划线)
    /// - `payload`: 通知载荷字符串(单引号自动转义)
    ///
    /// # 错误
    ///
    /// - 通道名包含非法字符时返回 `DbError::Internal`
    async fn notify(&mut self, channel: &str, payload: &str) -> Result<(), DbError>;

    /// COPY FROM STDIN:批量导入数据
    ///
    /// # 参数
    ///
    /// - `sql`: COPY 语句,如 `COPY mytable (col1, col2) FROM STDIN WITH (FORMAT csv, HEADER true)`
    /// - `data`: 完整的导入数据字节流
    ///
    /// # 返回
    ///
    /// 返回受影响的行数。
    ///
    /// # 性能
    ///
    /// 比逐行 INSERT 快 10~100 倍,适用于大批量数据导入(10 万行以上)。
    async fn copy_from_stdin(&mut self, sql: &str, data: &[u8]) -> Result<u64, DbError>;
}

/// 校验 PostgreSQL 通道名合法性(仅允许字母、数字、下划线)
///
/// LISTEN/NOTIFY 的通道名不能通过参数化绑定,必须拼接 SQL,
/// 因此需严格校验防止 SQL 注入。
fn validate_pg_channel_name(channel: &str) -> Result<(), DbError> {
    if channel.is_empty() {
        return Err(DbError::Internal(
            "PG channel name must not be empty".to_string(),
        ));
    }
    if !channel
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '_')
    {
        return Err(DbError::Internal(format!(
            "invalid PG channel name: {} (only alphanumeric and underscore allowed)",
            channel
        )));
    }
    Ok(())
}

#[async_trait]
impl PgExtensions for SqlxPgConnection {
    async fn listen(&mut self, channel: &str) -> Result<(), DbError> {
        validate_pg_channel_name(channel)?;
        // LISTEN 是简单 SQL 命令,channel 已校验,可安全拼接
        self.execute(&format!("LISTEN {}", channel)).await?;
        Ok(())
    }

    async fn notify(&mut self, channel: &str, payload: &str) -> Result<(), DbError> {
        validate_pg_channel_name(channel)?;
        // payload 通过 PostgreSQL 字符串字面量转义(单引号加倍)防止注入
        let escaped_payload = payload.replace('\'', "''");
        self.execute(&format!("NOTIFY {}, '{}'", channel, escaped_payload))
            .await?;
        Ok(())
    }

    async fn copy_from_stdin(&mut self, sql: &str, data: &[u8]) -> Result<u64, DbError> {
        let mut pool_conn = self
            .conn
            .take()
            .ok_or_else(|| DbError::Internal("connection already closed".to_string()))?;
        // sqlx 0.9: 通过 DerefMut 访问 PgConnection 的 copy_in_raw 方法
        // 启动 COPY 协议,返回 PgCopyIn 流式写入句柄
        // 注意:直接使用 *pool_conn 解引用,避免 clippy::needless_borrow 警告
        let mut copy = (*pool_conn)
            .copy_in_raw(sql)
            .await
            .map_err(map_sqlx_error)?;
        // 一次性发送全部数据(非流式,适用于数据可完整载入内存的场景)
        copy.send(data).await.map_err(map_sqlx_error)?;
        // 完成 COPY 操作,sqlx 0.9 的 PgCopyIn::finish() 直接返回 u64(受影响行数)
        let result = copy.finish().await.map_err(map_sqlx_error)?;
        self.conn = Some(pool_conn);
        Ok(result)
    }
}

/// PostgreSQL 批量导入(多行 INSERT,作为 COPY 协议的简化替代)
///
/// 构建多行 INSERT 语句:`INSERT INTO t (c1, c2) VALUES ($1, $2), ($3, $4), ...`
/// 使用参数绑定避免 SQL 注入。PostgreSQL 占位符 `$N` 跨行递增。
///
/// 当数据量极大(>10 万行)时,建议分批调用或使用
/// [`PgExtensions::copy_from_stdin`] 走 COPY 协议以获得更高吞吐。
pub async fn pg_bulk_insert(
    conn: &mut SqlxPgConnection,
    table: &str,
    columns: &[&str],
    rows: &[Vec<Value>],
) -> Result<u64, DbError> {
    if rows.is_empty() {
        return Ok(0);
    }
    let col_list = columns.join(", ");
    let cols_per_row = columns.len();
    // PostgreSQL 占位符 $1, $2, ... 跨行递增
    let placeholders: Vec<String> = rows
        .iter()
        .enumerate()
        .map(|(row_idx, _)| {
            let base = row_idx * cols_per_row;
            let ph: Vec<String> = (0..cols_per_row)
                .map(|i| format!("${}", base + i + 1))
                .collect();
            format!("({})", ph.join(", "))
        })
        .collect();
    let sql = format!(
        "INSERT INTO {} ({}) VALUES {}",
        table,
        col_list,
        placeholders.join(", ")
    );
    // 展平所有行的值为单一参数数组
    let mut params: Vec<Value> = Vec::with_capacity(rows.len() * cols_per_row);
    for row in rows {
        for v in row {
            params.push(v.clone());
        }
    }
    conn.execute_with_params(&sql, &params).await
}