sz-orm-core 1.2.2

Core ORM engine: Model trait, ActiveRecord, QueryBuilder, Pool, Transaction, migration, and SQL dialect abstraction
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
//! 模型抽象层
//!
//! 提供核心 `Model` trait 及相关类型

use crate::async_trait;
use crate::Value;
use std::collections::HashMap;
use std::fmt;
use thiserror::Error;

/// 所有 ORM 模型必须实现的核心 trait
///
/// L-5 修复:补充示例文档
///
/// # 示例
///
/// ```ignore
/// use sz_orm_core::model::Model;
///
/// #[derive(Debug, Clone, Default)]
/// struct User {
///     id: i64,
///     name: String,
/// }
///
/// impl Model for User {
///     type PrimaryKey = i64;
///     fn table_name() -> &'static str { "users" }
///     fn pk(&self) -> Self::PrimaryKey { self.id }
///     fn set_pk(&mut self, pk: Self::PrimaryKey) { self.id = pk; }
/// }
///
/// assert_eq!(User::table_name(), "users");
/// assert_eq!(User::pk_name(), "id");
/// assert_eq!(User::foreign_key("orders"), "orders_id");
/// ```
pub trait Model: Send + Sync + Sized + 'static {
    /// 主键类型
    type PrimaryKey: Send + Sync + fmt::Debug + fmt::Display + Clone + Default;

    /// 获取该模型对应的表名
    fn table_name() -> &'static str;

    /// 获取主键列名(默认 `id`)
    fn pk_name() -> &'static str {
        "id"
    }

    /// 获取当前实例的主键值
    fn pk(&self) -> Self::PrimaryKey;

    /// 设置当前实例的主键值
    fn set_pk(&mut self, pk: Self::PrimaryKey);

    /// 根据关系名推导外键名(默认 `<relation>_id`)
    ///
    /// M-9 说明:默认将 `relation` 转为小写后拼接 `_id`。
    /// 对于大小写敏感的列名(如 PostgreSQL 的 `User_ID`),业务模型应重写此方法。
    fn foreign_key(relation: &str) -> String {
        format!("{}_id", relation.to_lowercase())
    }

    /// 获取自动时间戳字段配置
    fn timestamp_fields() -> Option<TimestampFields> {
        None
    }

    /// 获取软删除字段名
    fn soft_delete_field() -> Option<&'static str> {
        None
    }

    /// 获取多租户字段名(P0-3)
    ///
    /// 返回 `Some(field)` 表示该模型支持多租户,`QueryBuilder` 会在
    /// `with_tenant_id(id)` 设置租户 ID 后自动追加 `WHERE {field} = ?` 条件。
    ///
    /// 默认返回 `None`(非多租户模型)。多租户模型应重写此方法返回字段名,
    /// 如 `Some("tenant_id")`。
    ///
    /// 与 `TenantModel` trait 的关系:`TenantModel::tenant_field()` 返回 `&'static str`
    /// (非 Option),用于实例级的 `tenant_id()`/`set_tenant_id()` 操作;
    /// 本方法返回 `Option<&'static str>`,用于 `QueryBuilder` 静态判断模型是否多租户。
    fn tenant_field() -> Option<&'static str> {
        None
    }

    /// 获取字段定义(字段名, 类型字符串),用于 OpenAPI schema 生成等
    ///
    /// 类型字符串遵循 sz-orm casts 约定:
    /// `"integer"` / `"float"` / `"boolean"` / `"string"` / `"datetime"` / `"date"` /
    /// `"time"` / `"json"` / `"array"` / `"bytes"`。
    ///
    /// 默认返回空列表;需要 schema 推导的模型应重写此方法。
    fn fields() -> Vec<(&'static str, &'static str)> {
        vec![]
    }
}

/// 时间戳字段配置
#[derive(Debug, Clone, Default)]
pub struct TimestampFields {
    /// created_at 字段名
    pub created_at: Option<&'static str>,
    /// updated_at 字段名
    pub updated_at: Option<&'static str>,
    /// 插入时是否自动设置时间戳
    pub auto_now_insert: bool,
    /// 更新时是否自动刷新时间戳
    pub auto_now_update: bool,
}

impl TimestampFields {
    pub fn new(created_at: Option<&'static str>, updated_at: Option<&'static str>) -> Self {
        Self {
            created_at,
            updated_at,
            auto_now_insert: created_at.is_some(),
            auto_now_update: updated_at.is_some(),
        }
    }

    pub fn with_both(created_at: &'static str, updated_at: &'static str) -> Self {
        Self {
            created_at: Some(created_at),
            updated_at: Some(updated_at),
            auto_now_insert: true,
            auto_now_update: true,
        }
    }
}

/// 模型间的关系描述
#[derive(Debug, Clone)]
pub enum Relation {
    /// 多对一关系(如 Order 属于 User)
    BelongsTo(BelongsTo),
    /// 一对多关系(如 User 有多个 Order)
    HasMany(HasMany),
    /// 一对一关系(如 User 有一个 Profile)
    HasOne(HasOne),
    /// 多对多关系(通过中间表,如 User 与 Role)
    BelongsToMany(BelongsToMany),
    /// 多态一对多(如 Comment 可关联 Post / Video / Image 等多种父模型)
    /// 子表通过 morph_type_column + morph_id_column 反向定位父模型
    MorphMany(MorphMany),
    /// 多态反向:当前模型可被多种父模型拥有(当前模型持有 morph_type + morph_id 两列)
    MorphTo(MorphTo),
}

/// 多对一关系配置
#[derive(Debug, Clone)]
pub struct BelongsTo {
    pub foreign_key: String,
    pub parent_model: String,
    pub parent_pk: String,
}

/// 一对多关系配置
#[derive(Debug, Clone)]
pub struct HasMany {
    pub foreign_key: String,
    pub child_model: String,
    pub child_pk: String,
}

/// 一对一关系配置
#[derive(Debug, Clone)]
pub struct HasOne {
    pub foreign_key: String,
    pub child_model: String,
    pub child_pk: String,
}

/// 多对多关系配置
///
/// 关联语义:
/// - `junction_table`:中间表名(如 `user_roles`)
/// - `foreign_key`:中间表中指向当前模型主键的列名(如 `user_id`)
/// - `other_key`:中间表中指向目标模型主键的列名(如 `role_id`)
/// - `target_model`:目标表名(如 `roles`)
/// - `target_pk`:目标表的主键列名(如 `id`),用于 JOIN 条件 `t.{target_pk} = j.{other_key}`
#[derive(Debug, Clone)]
pub struct BelongsToMany {
    pub junction_table: String,
    pub foreign_key: String,
    pub other_key: String,
    pub target_model: String,
    pub target_pk: String,
}

/// 多态一对多配置(父模型侧)
///
/// 例:Post has many Comment,Comment 表中有 `commentable_type`(值为 "Post")和 `commentable_id` 两列。
/// 加载 Post.comments 时:`SELECT * FROM comments WHERE commentable_type = 'Post' AND commentable_id = ?`
#[derive(Debug, Clone)]
pub struct MorphMany {
    /// 子模型表名(如 "comments")
    pub child_model: String,
    /// 子表中标识父类型的列名(如 "commentable_type")
    pub morph_type_column: String,
    /// 子表中标识父主键的列名(如 "commentable_id")
    pub morph_id_column: String,
    /// 父模型类型标识字符串(如 "Post")
    pub morph_type_value: String,
}

/// 多态反向配置(子模型侧)
///
/// 例:Comment 属于 Post 或 Video,Comment 表中有 `commentable_type` + `commentable_id`。
/// 加载 Comment.commentable 时,根据 commentable_type 路由到不同表。
#[derive(Debug, Clone)]
pub struct MorphTo {
    /// 当前模型中标识父类型的列名(如 "commentable_type")
    pub morph_type_column: String,
    /// 当前模型中标识父主键的列名(如 "commentable_id")
    pub morph_id_column: String,
}

/// 支持关系加载的模型 trait(ActiveRecord 模式)
///
/// L-5 修复:补充示例文档
///
/// # 示例
///
/// ```ignore
/// use sz_orm_core::model::{Model, ActiveRecord};
///
/// #[derive(Debug, Clone, Default)]
/// struct User { id: i64, name: String }
///
/// impl Model for User {
///     type PrimaryKey = i64;
///     fn table_name() -> &'static str { "users" }
///     fn pk(&self) -> Self::PrimaryKey { self.id }
///     fn set_pk(&mut self, pk: Self::PrimaryKey) { self.id = pk; }
/// }
///
/// // 假设已实现 ModelExt + RelationLoader
/// impl ActiveRecord for User {}
///
/// // 通过 with() 链式预加载多个关系
/// let user = User { id: 1, name: "Alice".into() }
///     .with("orders")
///     .with("profile");
/// ```
#[async_trait]
pub trait ActiveRecord: Model + ModelExt + RelationLoader + Clone + Send + Sync {
    /// 预加载指定关系
    /// 用法:`user.with("orders").with("profile").load(&mut conn).await`
    fn with(self, relation: &str) -> WithRelation<Self> {
        WithRelation {
            model: self,
            relations: vec![relation.to_string()],
        }
    }

    /// 一次性预加载多个关系
    fn with_all(self, relations: Vec<&str>) -> WithRelation<Self> {
        WithRelation {
            model: self,
            relations: relations.into_iter().map(|s| s.to_string()).collect(),
        }
    }
}

/// 关系预加载构造器
///
/// # Send 约束
///
/// `WithRelation<M>` 显式要求 `M: Send`,与 `ActiveRecord: Send + Sync` 保持一致。
/// 这确保返回值可安全地跨线程传递(如通过 tokio::spawn)。
///
/// # Compile-time Send 保证
///
/// 通过下方 `impl` 块的 `where Self: Send` 子句强制保证:
/// 任何满足约束的 `M` 生成的 `WithRelation<M>` 都自动满足 `Send`。
/// 如果未来 `WithRelation` 字段变更导致不再 `Send`(如使用 `Rc`/`Cell`),编译期即报错。
pub struct WithRelation<M: Model + ModelExt + RelationLoader + Send> {
    model: M,
    relations: Vec<String>,
}

// 编译期 Send 断言:通过空 impl 强制 WithRelation<M>: Send
// 借助 where Self: Send 子句,若未来字段变更破坏 Send 性质,此 impl 将无法编译
impl<M: Model + ModelExt + RelationLoader + Send> WithRelation<M> where Self: Send {}

/// 转义 SQL 字符串字面量中的特殊字符(用于内嵌值场景)
///
/// 将单引号 `'` 替换为 `''`,将反斜杠 `\` 替换为 `\\`。
/// 该函数仅对需要内嵌到 SQL 字符串字面量中的值使用,
/// 不要用于标识符(表名/列名)的转义。
///
/// L-1 修复:补全转义字符集,覆盖 MySQL/PostgreSQL/SQLite/Oracle/SQL Server
/// 标准字符串字面量中的特殊字符:
/// - `'` → `''`(标准 SQL 转义)
/// - `\` → `\\`(MySQL/SQLite 反斜杠转义)
/// - `\0` → `\0`(NUL 字符,MySQL/PostgreSQL 危险)
/// - `\n` → `\n`(换行)
/// - `\r` → `\r`(回车)
/// - `\x1a` → `\Z`(Ctrl+Z,Windows EOF,MySQL 危险)
/// - `"` → `\"`(双引号转义,防止误闭合标识符)
/// - `\x08` → `\b`(退格)
fn escape_sql_value(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    for ch in s.chars() {
        match ch {
            '\'' => out.push_str("''"),
            '\\' => out.push_str("\\\\"),
            '\0' => out.push_str("\\0"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\x1a' => out.push_str("\\Z"),
            '"' => out.push_str("\\\""),
            '\x08' => out.push_str("\\b"),
            _ => out.push(ch),
        }
    }
    out
}

/// 将主键值转换为安全的 SQL 字面量
///
/// - 纯数字(i64/u64/f64 可解析)→ 不加引号,直接返回
/// - 其他字符串 → 加单引号并转义内部特殊字符,防止 SQL 注入
fn pk_to_sql_string(pk: &dyn std::fmt::Display) -> String {
    let s = pk.to_string();
    if s.parse::<i64>().is_ok() || s.parse::<u64>().is_ok() || s.parse::<f64>().is_ok() {
        s
    } else {
        format!("'{}'", escape_sql_value(&s))
    }
}

/// 将任意字符串值转换为安全的 SQL 字符串字面量
///
/// 与 `pk_to_sql_string` 不同,本函数始终用单引号包裹并转义,
/// 适用于字符串类型的外键值等。
fn value_to_sql_string(s: &str) -> String {
    format!("'{}'", escape_sql_value(s))
}

/// 校验 SQL 标识符(表名/列名)是否合法
///
/// 合法标识符规则:
/// - 非空
/// - 仅包含字母、数字、下划线
/// - 首字符为字母或下划线
/// - 长度 ≤ 64(与大多数数据库一致)
///
/// 用于防止 MorphTo 关系加载中 morph_type_value 作为表名拼接时的 SQL 注入。
fn is_valid_sql_identifier(s: &str) -> bool {
    if s.is_empty() || s.len() > 64 {
        return false;
    }
    let mut chars = s.chars();
    match chars.next() {
        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
        _ => return false,
    }
    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

/// 批量校验关系加载中的所有 SQL 标识符
///
/// H-1 修复:所有关系加载(HasMany/HasOne/BelongsTo/BelongsToMany/MorphMany)在拼接 SQL 前
/// 必须校验表名、列名为合法标识符,防止 SQL 注入。
fn validate_relation_identifiers(idents: &[&str]) -> Result<(), RelationError> {
    for ident in idents {
        if !is_valid_sql_identifier(ident) {
            return Err(RelationError::QueryError(format!(
                "invalid SQL identifier in relation config (potential SQL injection): {}",
                ident
            )));
        }
    }
    Ok(())
}

impl<M: Model + ModelExt + RelationLoader + Send> WithRelation<M> {
    /// 追加一个待加载的关系
    pub fn with(mut self, relation: &str) -> Self {
        self.relations.push(relation.to_string());
        self
    }

    /// 加载所有指定关系并返回填充后的模型
    /// 加载结果通过 `set_relation_data` 写回模型
    pub async fn load<C>(self, conn: &mut C) -> Result<M, RelationError>
    where
        C: crate::pool::Connection + ?Sized,
    {
        let mut model = self.model;
        let relations_map = M::relations();

        for rel_name in &self.relations {
            let relation = relations_map
                .get(rel_name.as_str())
                .ok_or_else(|| RelationError::RelationNotFound(rel_name.clone()))?;

            match relation {
                Relation::HasMany(config) => {
                    let pk = model.pk();
                    let pk_str = pk_to_sql_string(&pk);
                    // H-1 修复:校验所有标识符,防止 SQL 注入
                    validate_relation_identifiers(&[&config.child_model, &config.foreign_key])?;
                    let sql = format!(
                        "SELECT * FROM {} WHERE {} = {}",
                        config.child_model, config.foreign_key, pk_str
                    );
                    let rows = conn
                        .query(&sql)
                        .await
                        .map_err(|e| RelationError::QueryError(e.to_string()))?;
                    model.set_relation_data(rel_name, rows_to_values(rows));
                }
                Relation::HasOne(config) => {
                    let pk = model.pk();
                    let pk_str = pk_to_sql_string(&pk);
                    // H-1 修复:校验所有标识符
                    validate_relation_identifiers(&[&config.child_model, &config.foreign_key])?;
                    let sql = format!(
                        "SELECT * FROM {} WHERE {} = {}",
                        config.child_model, config.foreign_key, pk_str
                    );
                    let rows = conn
                        .query(&sql)
                        .await
                        .map_err(|e| RelationError::QueryError(e.to_string()))?;
                    model.set_relation_data(rel_name, rows_to_values(rows));
                }
                Relation::BelongsTo(config) => {
                    let fk_value = model.get_relation_fk_value(&config.foreign_key);
                    // H-1 修复:校验所有标识符
                    validate_relation_identifiers(&[
                        &config.parent_model,
                        &config.parent_pk,
                        &config.foreign_key,
                    ])?;
                    let sql = format!(
                        "SELECT * FROM {} WHERE {} = {}",
                        config.parent_model,
                        config.parent_pk,
                        pk_to_sql_string(&fk_value)
                    );
                    let rows = conn
                        .query(&sql)
                        .await
                        .map_err(|e| RelationError::QueryError(e.to_string()))?;
                    model.set_relation_data(rel_name, rows_to_values(rows));
                }
                Relation::BelongsToMany(config) => {
                    let pk = model.pk();
                    let pk_str = pk_to_sql_string(&pk);
                    // H-1 修复:校验所有标识符
                    validate_relation_identifiers(&[
                        &config.target_model,
                        &config.junction_table,
                        &config.target_pk,
                        &config.other_key,
                        &config.foreign_key,
                    ])?;
                    // JOIN 条件:目标表 t 的主键 = 中间表 j 的 other_key
                    // 过滤条件:中间表 j 的 foreign_key = 当前模型主键
                    let sql = format!(
                        "SELECT t.* FROM {} t INNER JOIN {} j ON t.{} = j.{} WHERE j.{} = {}",
                        config.target_model,
                        config.junction_table,
                        config.target_pk,
                        config.other_key,
                        config.foreign_key,
                        pk_str
                    );
                    let rows = conn
                        .query(&sql)
                        .await
                        .map_err(|e| RelationError::QueryError(e.to_string()))?;
                    model.set_relation_data(rel_name, rows_to_values(rows));
                }
                Relation::MorphMany(config) => {
                    let pk = model.pk();
                    let pk_str = pk_to_sql_string(&pk);
                    // H-1 修复:校验所有标识符(morph_type_value 为字面量,已转义)
                    validate_relation_identifiers(&[
                        &config.child_model,
                        &config.morph_type_column,
                        &config.morph_id_column,
                    ])?;
                    // SELECT * FROM comments WHERE commentable_type = 'Post' AND commentable_id = <pk>
                    let sql = format!(
                        "SELECT * FROM {} WHERE {} = {} AND {} = {}",
                        config.child_model,
                        config.morph_type_column,
                        value_to_sql_string(&config.morph_type_value),
                        config.morph_id_column,
                        pk_str
                    );
                    let rows = conn
                        .query(&sql)
                        .await
                        .map_err(|e| RelationError::QueryError(e.to_string()))?;
                    model.set_relation_data(rel_name, rows_to_values(rows));
                }
                Relation::MorphTo(config) => {
                    // 根据当前模型持有的 morph_type_column 值路由到不同表
                    // 实现侧需通过 get_relation_fk_value 提供两个值:type 与 id
                    // 为保持与 RelationLoader 接口兼容,这里采用约定:
                    //   get_relation_fk_value("<morph_type_column>") 返回 type 字符串
                    //   get_relation_fk_value("<morph_id_column>")   返回 id 字符串
                    let morph_type_value = model.get_relation_fk_value(&config.morph_type_column);
                    let morph_id_value = model.get_relation_fk_value(&config.morph_id_column);
                    if morph_type_value.is_empty() || morph_id_value.is_empty() {
                        // 无父模型关联(morph_type 为空),置空数组
                        model.set_relation_data(rel_name, Value::Array(vec![]));
                    } else {
                        // 约定:morph_type_value 即为目标表名(Post → "posts"),由调用方在 get_relation_fk_value 中映射
                        // C-2 修复:morph_type_value 作为表名拼接前必须校验为合法标识符,防止 SQL 注入
                        if !is_valid_sql_identifier(&morph_type_value) {
                            return Err(RelationError::QueryError(format!(
                                "invalid morph_type_value (not a valid SQL identifier): {}",
                                morph_type_value
                            )));
                        }
                        let sql = format!(
                            "SELECT * FROM {} WHERE id = {}",
                            morph_type_value,
                            pk_to_sql_string(&morph_id_value)
                        );
                        let rows = conn
                            .query(&sql)
                            .await
                            .map_err(|e| RelationError::QueryError(e.to_string()))?;
                        model.set_relation_data(rel_name, rows_to_values(rows));
                    }
                }
            }
        }

        Ok(model)
    }
}

/// 将查询结果行转换为 `Vec<HashMap<String, Value>>` 以便存入关系字段
pub fn rows_to_values(rows: Vec<HashMap<String, Value>>) -> Value {
    if rows.is_empty() {
        return Value::Array(vec![]);
    }
    let items: Vec<Value> = rows
        .into_iter()
        .map(|row| {
            let mut map = HashMap::new();
            for (k, v) in row {
                map.insert(k, v);
            }
            Value::from_map(map)
        })
        .collect();
    Value::Array(items)
}

/// 关系操作错误类型
#[derive(Error, Debug, Clone)]
pub enum RelationError {
    #[error("Relation '{0}' not found in model relations")]
    RelationNotFound(String),

    #[error("Query error during relation loading: {0}")]
    QueryError(String),

    #[error("Relation data not loaded. Call .with(\"{0}\") before accessing.")]
    NotLoaded(String),
}

/// 可存储已加载关系数据的模型 trait
pub trait RelationLoader: Model {
    /// 获取已加载的关系数据
    fn get_relation(&self, name: &str) -> Option<&Value>;

    /// 写入已加载的关系数据
    fn set_relation_data(&mut self, name: &str, data: Value);

    /// 获取关系对应的外键值
    fn get_relation_fk_value(&self, fk_name: &str) -> String;
}

/// `ModelExt` 的关系访问扩展方法
pub trait RelationAccess: ModelExt {
    /// 获取一对多关系数据(必须先调用 `.with(name)` 加载)
    fn get_has_many(&self, name: &str) -> Result<Vec<HashMap<String, Value>>, RelationError>
    where
        Self: RelationLoader,
    {
        let data = self
            .get_relation(name)
            .ok_or_else(|| RelationError::NotLoaded(name.to_string()))?;
        match data {
            Value::Array(items) => {
                let result: Vec<HashMap<String, Value>> = items
                    .iter()
                    .filter_map(|v| match v {
                        Value::Object(map) => Some(map.clone()),
                        _ => None,
                    })
                    .collect();
                Ok(result)
            }
            _ => Ok(vec![]),
        }
    }

    /// 获取一对一或多对一关系数据(必须先加载,返回 0 或 1 行)
    fn get_has_one(&self, name: &str) -> Result<Option<HashMap<String, Value>>, RelationError>
    where
        Self: RelationLoader,
    {
        let data = self
            .get_relation(name)
            .ok_or_else(|| RelationError::NotLoaded(name.to_string()))?;
        match data {
            Value::Array(items) => {
                if items.is_empty() {
                    Ok(None)
                } else {
                    match &items[0] {
                        Value::Object(map) => Ok(Some(map.clone())),
                        _ => Ok(None),
                    }
                }
            }
            _ => Ok(None),
        }
    }

    /// 获取多对多关系数据(必须先加载)
    fn get_belongs_to_many(&self, name: &str) -> Result<Vec<HashMap<String, Value>>, RelationError>
    where
        Self: RelationLoader,
    {
        self.get_has_many(name)
    }

    /// 获取多态一对多关系数据(必须先加载)
    /// 与 has_many 行为一致,返回多行
    fn get_morph_many(&self, name: &str) -> Result<Vec<HashMap<String, Value>>, RelationError>
    where
        Self: RelationLoader,
    {
        self.get_has_many(name)
    }

    /// 获取多态反向关系数据(必须先加载)
    /// 与 has_one 行为一致,返回 0 或 1 行
    fn get_morph_to(&self, name: &str) -> Result<Option<HashMap<String, Value>>, RelationError>
    where
        Self: RelationLoader,
    {
        self.get_has_one(name)
    }
}

/// 查询结果过滤作用域
pub trait Scope: Send + Sync {
    /// 将作用域应用到查询构造器
    fn apply<M: Model>(&self, query: &mut QueryBuilderWrapper<M>);
}

/// 查询构造器包装类型,用于挂载作用域
pub struct QueryBuilderWrapper<'a, M: Model> {
    pub builder: &'a mut dyn QueryBuilderExt<Model = M>,
}

pub trait QueryBuilderExt: Send + Sync {
    type Model: Model;

    fn and_where(&mut self, condition: &str);
    fn or_where(&mut self, condition: &str);
}

/// 模型扩展 trait,提供额外功能
pub trait ModelExt: Model {
    /// 获取 SELECT 时使用的所有列
    fn columns() -> Vec<&'static str>;

    /// 获取可批量赋值的列(INSERT/UPDATE)
    fn fillable() -> Vec<&'static str>;

    /// 获取受保护列(不可批量赋值)
    fn guarded() -> Vec<&'static str> {
        vec![Self::pk_name()]
    }

    /// 获取隐藏列(不参与序列化)
    fn hidden() -> Vec<&'static str> {
        vec![]
    }

    /// 获取可见列(参与序列化)
    fn visible() -> Vec<&'static str> {
        vec![]
    }

    /// 获取类型转换映射(列名 -> 类型字符串)
    fn casts() -> std::collections::HashMap<&'static str, &'static str> {
        std::collections::HashMap::new()
    }

    /// 获取日期列
    fn dates() -> Vec<&'static str> {
        vec![]
    }

    /// 获取指定字段的日期格式
    fn date_format(_field: &str) -> Option<&'static str> {
        None
    }

    /// 获取关系映射
    fn relations() -> std::collections::HashMap<&'static str, Relation> {
        std::collections::HashMap::new()
    }

    /// 将模型转换为值映射
    fn to_value(&self) -> std::collections::HashMap<String, Value> {
        let mut map = std::collections::HashMap::new();
        for col in Self::columns() {
            if let Some(val) = Self::get_column_value(self, col) {
                // 跳过 hidden 字段
                if !Self::hidden().contains(&col) {
                    map.insert(col.to_string(), val);
                }
            }
        }
        map
    }

    /// 获取指定列的值(须由实现重写)
    fn get_column_value(&self, _column: &str) -> Option<Value> {
        None
    }

    /// 从值映射还原模型(须由实现重写)
    #[allow(clippy::wrong_self_convention)]
    fn from_value(&mut self, _map: std::collections::HashMap<String, Value>) {
        // 默认空实现,业务模型须重写
    }

    /// 批量赋值:只填充 fillable 字段(过滤掉 guarded 字段)
    fn fill(&mut self, mut map: std::collections::HashMap<String, Value>) {
        let guarded = Self::guarded();
        let fillable = Self::fillable();
        // 移除 guarded 字段
        for g in &guarded {
            map.remove(*g);
        }
        // 如果 fillable 非空,只保留 fillable 字段
        if !fillable.is_empty() {
            map.retain(|k, _| fillable.contains(&k.as_str()));
        }
        self.from_value(map);
    }

    /// 序列化为 JSON
    fn to_json(&self) -> serde_json::Value {
        let map = self.to_value();
        let mut obj = serde_json::Map::new();
        for (k, v) in map {
            obj.insert(k, value_to_json(v));
        }
        serde_json::Value::Object(obj)
    }
}

/// 将 Value 转换为 serde_json::Value(递归处理 Array)
pub fn value_to_json(v: Value) -> serde_json::Value {
    match v {
        Value::Null => serde_json::Value::Null,
        Value::Bool(b) => serde_json::Value::Bool(b),
        Value::I8(n) => serde_json::Value::Number(serde_json::Number::from(n)),
        Value::I16(n) => serde_json::Value::Number(serde_json::Number::from(n)),
        Value::I32(n) => serde_json::Value::Number(serde_json::Number::from(n)),
        Value::I64(n) => serde_json::Value::Number(serde_json::Number::from(n)),
        Value::U8(n) => serde_json::Value::Number(serde_json::Number::from(n)),
        Value::U16(n) => serde_json::Value::Number(serde_json::Number::from(n)),
        Value::U32(n) => serde_json::Value::Number(serde_json::Number::from(n)),
        Value::U64(n) => serde_json::Value::Number(serde_json::Number::from(n)),
        Value::F32(n) => serde_json::Number::from_f64(n as f64)
            .map(serde_json::Value::Number)
            .unwrap_or(serde_json::Value::Null),
        Value::F64(n) => serde_json::Number::from_f64(n)
            .map(serde_json::Value::Number)
            .unwrap_or(serde_json::Value::Null),
        Value::String(s) => serde_json::Value::String(s),
        Value::Bytes(b) => {
            // M-1 修复:使用查表法替代 format!("{:02x}", byte) 提升性能
            const HEX_LOWER: &[u8; 16] = b"0123456789abcdef";
            let mut s = String::with_capacity(b.len() * 2);
            for byte in b {
                s.push(HEX_LOWER[(byte >> 4) as usize] as char);
                s.push(HEX_LOWER[(byte & 0x0f) as usize] as char);
            }
            serde_json::Value::String(s)
        }
        Value::Uuid(s) | Value::Date(s) | Value::DateTime(s) | Value::Time(s) | Value::Json(s) => {
            serde_json::Value::String(s)
        }
        Value::Decimal(s) => serde_json::Value::String(s),
        Value::Array(arr) => serde_json::Value::Array(arr.into_iter().map(value_to_json).collect()),
        Value::Object(map) => {
            let mut obj = serde_json::Map::new();
            for (k, v) in map {
                obj.insert(k, value_to_json(v));
            }
            serde_json::Value::Object(obj)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_timestamp_fields() {
        let ts = TimestampFields::new(Some("created_at"), Some("updated_at"));
        assert!(ts.created_at.is_some());
        assert!(ts.updated_at.is_some());

        let ts2 = TimestampFields::with_both("created_at", "updated_at");
        assert!(ts2.auto_now_insert);
        assert!(ts2.auto_now_update);
    }

    #[test]
    fn test_foreign_key() {
        struct TestModel;
        impl Model for TestModel {
            type PrimaryKey = i64;

            fn table_name() -> &'static str {
                "test_models"
            }

            fn pk(&self) -> Self::PrimaryKey {
                1
            }

            fn set_pk(&mut self, _pk: Self::PrimaryKey) {}
        }

        let fk = TestModel::foreign_key("user");
        assert_eq!(fk, "user_id");

        let fk = TestModel::foreign_key("Role");
        assert_eq!(fk, "role_id");
    }

    #[test]
    fn test_relation_documentation() {
        // 验证 Relation 枚举的语义
        let belongs_to = Relation::BelongsTo(BelongsTo {
            foreign_key: "user_id".to_string(),
            parent_model: "User".to_string(),
            parent_pk: "id".to_string(),
        });
        if let Relation::BelongsTo(ref bt) = belongs_to {
            assert_eq!(bt.parent_model, "User");
        }

        let has_one = Relation::HasOne(HasOne {
            foreign_key: "user_id".to_string(),
            child_model: "Profile".to_string(),
            child_pk: "id".to_string(),
        });
        if let Relation::HasOne(ref ho) = has_one {
            assert_eq!(ho.child_model, "Profile");
        }

        let has_many = Relation::HasMany(HasMany {
            foreign_key: "user_id".to_string(),
            child_model: "Order".to_string(),
            child_pk: "id".to_string(),
        });
        if let Relation::HasMany(ref hm) = has_many {
            assert_eq!(hm.child_model, "Order");
        }

        let many_to_many = Relation::BelongsToMany(BelongsToMany {
            junction_table: "user_role".to_string(),
            foreign_key: "user_id".to_string(),
            other_key: "role_id".to_string(),
            target_model: "Role".to_string(),
            target_pk: "id".to_string(),
        });
        if let Relation::BelongsToMany(ref mtm) = many_to_many {
            assert_eq!(mtm.junction_table, "user_role");
            assert_eq!(mtm.target_pk, "id");
        }
    }

    #[test]
    fn test_model_ext_implementation() {
        /// 测试用的完整 ModelExt 实现
        struct UserModel {
            id: i64,
            name: String,
            email: String,
            password: String, // hidden
        }

        impl Model for UserModel {
            type PrimaryKey = i64;

            fn table_name() -> &'static str {
                "users"
            }

            fn pk(&self) -> Self::PrimaryKey {
                self.id
            }

            fn set_pk(&mut self, pk: Self::PrimaryKey) {
                self.id = pk;
            }
        }

        impl ModelExt for UserModel {
            fn columns() -> Vec<&'static str> {
                vec!["id", "name", "email", "password"]
            }

            fn fillable() -> Vec<&'static str> {
                vec!["name", "email", "password"]
            }

            fn hidden() -> Vec<&'static str> {
                vec!["password"]
            }

            fn get_column_value(&self, column: &str) -> Option<Value> {
                match column {
                    "id" => Some(Value::I64(self.id)),
                    "name" => Some(Value::String(self.name.clone())),
                    "email" => Some(Value::String(self.email.clone())),
                    "password" => Some(Value::String(self.password.clone())),
                    _ => None,
                }
            }

            fn from_value(&mut self, map: std::collections::HashMap<String, Value>) {
                if let Some(Value::I64(id)) = map.get("id") {
                    self.id = *id;
                }
                if let Some(Value::String(name)) = map.get("name") {
                    self.name = name.clone();
                }
                if let Some(Value::String(email)) = map.get("email") {
                    self.email = email.clone();
                }
                if let Some(Value::String(password)) = map.get("password") {
                    self.password = password.clone();
                }
            }
        }

        let user = UserModel {
            id: 1,
            name: "Alice".to_string(),
            email: "alice@example.com".to_string(),
            password: "secret".to_string(),
        };

        // 测试 to_value(应该跳过 hidden 字段)
        let values = user.to_value();
        assert!(values.contains_key("name"));
        assert!(values.contains_key("email"));
        // password 是 hidden,不应出现在 to_value 结果中
        assert!(!values.contains_key("password"));

        // 测试 to_json
        let json = user.to_json();
        assert!(json.is_object());
        assert!(json.get("name").is_some());
        assert!(json.get("password").is_none());

        // 测试 fill(应该过滤 guarded 字段)
        let mut user2 = UserModel {
            id: 0,
            name: String::new(),
            email: String::new(),
            password: String::new(),
        };
        let mut fill_data = std::collections::HashMap::new();
        fill_data.insert("id".to_string(), Value::I64(999)); // guarded, 应被过滤
        fill_data.insert("name".to_string(), Value::String("Bob".to_string()));
        fill_data.insert(
            "email".to_string(),
            Value::String("bob@example.com".to_string()),
        );
        fill_data.insert("password".to_string(), Value::String("hashed".to_string()));

        user2.fill(fill_data);
        // id 应保持 0(被过滤)
        assert_eq!(user2.id, 0);
        assert_eq!(user2.name, "Bob");
        assert_eq!(user2.email, "bob@example.com");
    }

    // ============= ActiveRecord 测试 =============

    use crate::pool::Connection;
    use std::pin::Pin;

    /// 模拟数据库连接,用于测试关系加载
    struct MockConnection {
        query_results: HashMap<String, Vec<HashMap<String, Value>>>,
    }

    impl Connection for MockConnection {
        fn execute<'a>(
            &'a mut self,
            _sql: &'a str,
        ) -> Pin<Box<dyn std::future::Future<Output = Result<u64, crate::DbError>> + Send + 'a>>
        {
            Box::pin(async { Ok(1) })
        }

        fn query<'a>(
            &'a mut self,
            sql: &'a str,
        ) -> Pin<
            Box<
                dyn std::future::Future<
                        Output = Result<Vec<HashMap<String, Value>>, crate::DbError>,
                    > + Send
                    + 'a,
            >,
        > {
            let result = self.query_results.get(sql).cloned().unwrap_or_default();
            Box::pin(async move { Ok(result) })
        }

        fn begin_transaction<'a>(
            &'a mut self,
        ) -> Pin<Box<dyn std::future::Future<Output = Result<(), crate::DbError>> + Send + 'a>>
        {
            Box::pin(async { Ok(()) })
        }

        fn commit<'a>(
            &'a mut self,
        ) -> Pin<Box<dyn std::future::Future<Output = Result<(), crate::DbError>> + Send + 'a>>
        {
            Box::pin(async { Ok(()) })
        }

        fn rollback<'a>(
            &'a mut self,
        ) -> Pin<Box<dyn std::future::Future<Output = Result<(), crate::DbError>> + Send + 'a>>
        {
            Box::pin(async { Ok(()) })
        }

        fn is_connected(&self) -> bool {
            true
        }

        fn ping<'a>(&'a mut self) -> Pin<Box<dyn std::future::Future<Output = bool> + Send + 'a>> {
            Box::pin(async { true })
        }

        fn close<'a>(
            &'a mut self,
        ) -> Pin<Box<dyn std::future::Future<Output = Result<(), crate::DbError>> + Send + 'a>>
        {
            Box::pin(async { Ok(()) })
        }
    }

    /// 测试用的 UserModel(带关系支持)
    #[derive(Clone)]
    #[allow(dead_code)]
    struct UserModel {
        id: i64,
        name: String,
        email: String,
        password: String,
        team_id: i64,
        relations: HashMap<String, Value>,
    }

    impl Model for UserModel {
        type PrimaryKey = i64;
        fn table_name() -> &'static str {
            "users"
        }
        fn pk(&self) -> Self::PrimaryKey {
            self.id
        }
        fn set_pk(&mut self, pk: Self::PrimaryKey) {
            self.id = pk;
        }
    }

    impl ModelExt for UserModel {
        fn columns() -> Vec<&'static str> {
            vec!["id", "name", "email", "team_id"]
        }
        fn fillable() -> Vec<&'static str> {
            vec!["name", "email"]
        }
        fn hidden() -> Vec<&'static str> {
            vec!["password"]
        }
        fn relations() -> HashMap<&'static str, Relation> {
            let mut map = HashMap::new();
            map.insert(
                "orders",
                Relation::HasMany(HasMany {
                    foreign_key: "user_id".to_string(),
                    child_model: "orders".to_string(),
                    child_pk: "id".to_string(),
                }),
            );
            map.insert(
                "profile",
                Relation::HasOne(HasOne {
                    foreign_key: "user_id".to_string(),
                    child_model: "profiles".to_string(),
                    child_pk: "id".to_string(),
                }),
            );
            map.insert(
                "team",
                Relation::BelongsTo(BelongsTo {
                    foreign_key: "team_id".to_string(),
                    parent_model: "teams".to_string(),
                    parent_pk: "id".to_string(),
                }),
            );
            map.insert(
                "roles",
                Relation::BelongsToMany(BelongsToMany {
                    junction_table: "user_roles".to_string(),
                    foreign_key: "user_id".to_string(),
                    other_key: "role_id".to_string(),
                    target_model: "roles".to_string(),
                    target_pk: "id".to_string(),
                }),
            );
            map.insert(
                "comments",
                Relation::MorphMany(MorphMany {
                    child_model: "comments".to_string(),
                    morph_type_column: "commentable_type".to_string(),
                    morph_id_column: "commentable_id".to_string(),
                    morph_type_value: "User".to_string(),
                }),
            );
            map
        }
        fn get_column_value(&self, column: &str) -> Option<Value> {
            match column {
                "id" => Some(Value::I64(self.id)),
                "name" => Some(Value::String(self.name.clone())),
                "email" => Some(Value::String(self.email.clone())),
                "team_id" => Some(Value::I64(self.team_id)),
                _ => None,
            }
        }
        fn from_value(&mut self, map: HashMap<String, Value>) {
            if let Some(Value::I64(id)) = map.get("id") {
                self.id = *id;
            }
            if let Some(Value::String(name)) = map.get("name") {
                self.name = name.clone();
            }
            if let Some(Value::String(email)) = map.get("email") {
                self.email = email.clone();
            }
            if let Some(Value::I64(tid)) = map.get("team_id") {
                self.team_id = *tid;
            }
        }
    }

    impl RelationLoader for UserModel {
        fn get_relation(&self, name: &str) -> Option<&Value> {
            self.relations.get(name)
        }
        fn set_relation_data(&mut self, name: &str, data: Value) {
            self.relations.insert(name.to_string(), data);
        }
        fn get_relation_fk_value(&self, fk_name: &str) -> String {
            match fk_name {
                "user_id" => format!("{}", self.id),
                "team_id" => format!("{}", self.team_id),
                _ => "0".to_string(),
            }
        }
    }

    impl ActiveRecord for UserModel {}
    impl RelationAccess for UserModel {}

    fn make_user() -> UserModel {
        UserModel {
            id: 1,
            name: "Alice".to_string(),
            email: "alice@example.com".to_string(),
            password: "secret".to_string(),
            team_id: 10,
            relations: HashMap::new(),
        }
    }

    fn make_order_row(id: i64, user_id: i64, total: &str) -> HashMap<String, Value> {
        let mut row = HashMap::new();
        row.insert("id".to_string(), Value::I64(id));
        row.insert("user_id".to_string(), Value::I64(user_id));
        row.insert("total".to_string(), Value::String(total.to_string()));
        row
    }

    fn make_profile_row(user_id: i64, bio: &str) -> HashMap<String, Value> {
        let mut row = HashMap::new();
        row.insert("id".to_string(), Value::I64(100));
        row.insert("user_id".to_string(), Value::I64(user_id));
        row.insert("bio".to_string(), Value::String(bio.to_string()));
        row
    }

    fn make_team_row(id: i64, name: &str) -> HashMap<String, Value> {
        let mut row = HashMap::new();
        row.insert("id".to_string(), Value::I64(id));
        row.insert("name".to_string(), Value::String(name.to_string()));
        row
    }

    fn make_role_row(id: i64, name: &str) -> HashMap<String, Value> {
        let mut row = HashMap::new();
        row.insert("id".to_string(), Value::I64(id));
        row.insert("name".to_string(), Value::String(name.to_string()));
        row
    }

    #[tokio::test]
    async fn test_active_record_with_has_many() {
        let user = make_user();
        let mut conn = MockConnection {
            query_results: {
                let mut m = HashMap::new();
                m.insert(
                    "SELECT * FROM orders WHERE user_id = 1".to_string(),
                    vec![
                        make_order_row(1, 1, "99.99"),
                        make_order_row(2, 1, "149.50"),
                    ],
                );
                m
            },
        };

        let user = user.with("orders").load(&mut conn).await.unwrap();
        let data = user.get_relation("orders");
        assert!(data.is_some());
        if let Some(Value::Array(items)) = data {
            assert_eq!(items.len(), 2);
        } else {
            panic!("Expected Array");
        }
    }

    #[tokio::test]
    async fn test_active_record_with_has_one() {
        let user = make_user();
        let mut conn = MockConnection {
            query_results: {
                let mut m = HashMap::new();
                m.insert(
                    "SELECT * FROM profiles WHERE user_id = 1".to_string(),
                    vec![make_profile_row(1, "Hello world")],
                );
                m
            },
        };

        let user = user.with("profile").load(&mut conn).await.unwrap();
        let data = user.get_relation("profile");
        assert!(data.is_some());
        if let Some(Value::Array(items)) = data {
            assert_eq!(items.len(), 1);
        }
    }

    #[tokio::test]
    async fn test_active_record_with_belongs_to() {
        let user = make_user();
        let mut conn = MockConnection {
            query_results: {
                let mut m = HashMap::new();
                m.insert(
                    "SELECT * FROM teams WHERE id = 10".to_string(),
                    vec![make_team_row(10, "Engineering")],
                );
                m
            },
        };

        let user = user.with("team").load(&mut conn).await.unwrap();
        let data = user.get_relation("team");
        assert!(data.is_some());
        if let Some(Value::Array(items)) = data {
            assert_eq!(items.len(), 1);
        }
    }

    #[tokio::test]
    async fn test_active_record_with_belongs_to_many() {
        let user = make_user();
        let mut conn = MockConnection {
            query_results: {
                let mut m = HashMap::new();
                m.insert(
                    "SELECT t.* FROM roles t INNER JOIN user_roles j ON t.id = j.role_id WHERE j.user_id = 1".to_string(),
                    vec![
                        make_role_row(1, "admin"),
                        make_role_row(2, "editor"),
                    ],
                );
                m
            },
        };

        let user = user.with("roles").load(&mut conn).await.unwrap();
        let data = user.get_relation("roles");
        assert!(data.is_some());
        if let Some(Value::Array(items)) = data {
            assert_eq!(items.len(), 2);
        }
    }

    #[tokio::test]
    async fn test_active_record_with_all() {
        let user = make_user();
        let mut conn = MockConnection {
            query_results: {
                let mut m = HashMap::new();
                m.insert(
                    "SELECT * FROM orders WHERE user_id = 1".to_string(),
                    vec![make_order_row(1, 1, "99.99")],
                );
                m.insert(
                    "SELECT * FROM profiles WHERE user_id = 1".to_string(),
                    vec![make_profile_row(1, "Bio")],
                );
                m
            },
        };

        let user = user
            .with_all(vec!["orders", "profile"])
            .load(&mut conn)
            .await
            .unwrap();

        assert!(user.get_relation("orders").is_some());
        assert!(user.get_relation("profile").is_some());
    }

    #[tokio::test]
    async fn test_active_record_relation_not_found() {
        let user = make_user();
        let mut conn = MockConnection {
            query_results: HashMap::new(),
        };

        let result = user.with("nonexistent").load(&mut conn).await;
        assert!(result.is_err());
        match result {
            Err(RelationError::RelationNotFound(name)) => {
                assert_eq!(name, "nonexistent");
            }
            _ => panic!("Expected RelationNotFound"),
        }
    }

    #[test]
    fn test_active_record_not_loaded() {
        let user = make_user();
        let result = user.get_has_many("orders");
        assert!(result.is_err());
        match result {
            Err(RelationError::NotLoaded(name)) => {
                assert_eq!(name, "orders");
            }
            _ => panic!("Expected NotLoaded"),
        }
    }

    #[test]
    fn test_rows_to_values_empty() {
        let rows: Vec<HashMap<String, Value>> = vec![];
        let result = rows_to_values(rows);
        assert_eq!(result, Value::Array(vec![]));
    }

    #[test]
    fn test_rows_to_values_with_data() {
        let mut row = HashMap::new();
        row.insert("id".to_string(), Value::I64(1));
        row.insert("name".to_string(), Value::String("test".to_string()));
        let rows = vec![row];
        let result = rows_to_values(rows);

        match &result {
            Value::Array(items) => {
                assert_eq!(items.len(), 1);
                assert!(items[0].is_object());
            }
            _ => panic!("Expected Array"),
        }
    }

    #[tokio::test]
    async fn test_relation_access_has_many() {
        let mut conn = MockConnection {
            query_results: {
                let mut m = HashMap::new();
                m.insert(
                    "SELECT * FROM orders WHERE user_id = 1".to_string(),
                    vec![
                        make_order_row(1, 1, "99.99"),
                        make_order_row(2, 1, "149.50"),
                    ],
                );
                m
            },
        };

        let user = make_user().with("orders").load(&mut conn).await.unwrap();
        let orders = user.get_has_many("orders").unwrap();
        assert_eq!(orders.len(), 2);
        assert_eq!(
            orders[0].get("total").unwrap(),
            &Value::String("99.99".to_string())
        );
    }

    #[tokio::test]
    async fn test_relation_access_has_one() {
        let mut conn = MockConnection {
            query_results: {
                let mut m = HashMap::new();
                m.insert(
                    "SELECT * FROM profiles WHERE user_id = 1".to_string(),
                    vec![make_profile_row(1, "My bio")],
                );
                m
            },
        };

        let user = make_user().with("profile").load(&mut conn).await.unwrap();
        let profile = user.get_has_one("profile").unwrap();
        assert!(profile.is_some());
        assert_eq!(
            profile.unwrap().get("bio").unwrap(),
            &Value::String("My bio".to_string())
        );
    }

    #[test]
    fn test_value_object() {
        let mut map = HashMap::new();
        map.insert("key".to_string(), Value::String("value".to_string()));
        let obj = Value::from_map(map);
        assert!(obj.is_object());

        if let Value::Object(m) = &obj {
            assert_eq!(m.get("key").unwrap(), &Value::String("value".to_string()));
        } else {
            panic!("Expected Object");
        }
    }

    // ============= 多态关联(MorphMany / MorphTo)测试 =============

    fn make_comment_row(
        id: i64,
        commentable_type: &str,
        commentable_id: i64,
        body: &str,
    ) -> HashMap<String, Value> {
        let mut row = HashMap::new();
        row.insert("id".to_string(), Value::I64(id));
        row.insert(
            "commentable_type".to_string(),
            Value::String(commentable_type.to_string()),
        );
        row.insert("commentable_id".to_string(), Value::I64(commentable_id));
        row.insert("body".to_string(), Value::String(body.to_string()));
        row
    }

    /// CommentModel:带 MorphTo 关系,演示多态反向关联
    /// comments 表结构:id, commentable_type ('User'/'Post'/'Video'), commentable_id, body
    #[derive(Clone)]
    #[allow(dead_code)]
    struct CommentModel {
        id: i64,
        commentable_type: String,
        commentable_id: i64,
        body: String,
        relations: HashMap<String, Value>,
    }

    impl Model for CommentModel {
        type PrimaryKey = i64;
        fn table_name() -> &'static str {
            "comments"
        }
        fn pk(&self) -> Self::PrimaryKey {
            self.id
        }
        fn set_pk(&mut self, pk: Self::PrimaryKey) {
            self.id = pk;
        }
    }

    impl ModelExt for CommentModel {
        fn columns() -> Vec<&'static str> {
            vec!["id", "commentable_type", "commentable_id", "body"]
        }
        fn fillable() -> Vec<&'static str> {
            vec!["commentable_type", "commentable_id", "body"]
        }
        fn relations() -> HashMap<&'static str, Relation> {
            let mut map = HashMap::new();
            map.insert(
                "commentable",
                Relation::MorphTo(MorphTo {
                    morph_type_column: "commentable_type".to_string(),
                    morph_id_column: "commentable_id".to_string(),
                }),
            );
            map
        }
        fn get_column_value(&self, column: &str) -> Option<Value> {
            match column {
                "id" => Some(Value::I64(self.id)),
                "commentable_type" => Some(Value::String(self.commentable_type.clone())),
                "commentable_id" => Some(Value::I64(self.commentable_id)),
                "body" => Some(Value::String(self.body.clone())),
                _ => None,
            }
        }
        fn from_value(&mut self, map: HashMap<String, Value>) {
            if let Some(Value::I64(id)) = map.get("id") {
                self.id = *id;
            }
            if let Some(Value::String(s)) = map.get("commentable_type") {
                self.commentable_type = s.clone();
            }
            if let Some(Value::I64(n)) = map.get("commentable_id") {
                self.commentable_id = *n;
            }
            if let Some(Value::String(s)) = map.get("body") {
                self.body = s.clone();
            }
        }
    }

    impl RelationLoader for CommentModel {
        fn get_relation(&self, name: &str) -> Option<&Value> {
            self.relations.get(name)
        }
        fn set_relation_data(&mut self, name: &str, data: Value) {
            self.relations.insert(name.to_string(), data);
        }
        fn get_relation_fk_value(&self, fk_name: &str) -> String {
            // MorphTo 约定:
            //  - 当 fk_name == morph_type_column 时,返回目标表名(这里 'User' → 'users')
            //  - 当 fk_name == morph_id_column  时,返回父模型主键值
            match fk_name {
                "commentable_type" => match self.commentable_type.as_str() {
                    "User" => "users".to_string(),
                    "Post" => "posts".to_string(),
                    "Video" => "videos".to_string(),
                    _ => String::new(),
                },
                "commentable_id" => format!("{}", self.commentable_id),
                _ => "0".to_string(),
            }
        }
    }

    impl ActiveRecord for CommentModel {}
    impl RelationAccess for CommentModel {}

    fn make_comment() -> CommentModel {
        CommentModel {
            id: 50,
            commentable_type: "User".to_string(),
            commentable_id: 1,
            body: "Hello!".to_string(),
            relations: HashMap::new(),
        }
    }

    #[test]
    fn test_morph_many_struct_fields() {
        let m = MorphMany {
            child_model: "comments".to_string(),
            morph_type_column: "commentable_type".to_string(),
            morph_id_column: "commentable_id".to_string(),
            morph_type_value: "Post".to_string(),
        };
        assert_eq!(m.child_model, "comments");
        assert_eq!(m.morph_type_column, "commentable_type");
        assert_eq!(m.morph_id_column, "commentable_id");
        assert_eq!(m.morph_type_value, "Post");
    }

    #[test]
    fn test_morph_to_struct_fields() {
        let m = MorphTo {
            morph_type_column: "commentable_type".to_string(),
            morph_id_column: "commentable_id".to_string(),
        };
        assert_eq!(m.morph_type_column, "commentable_type");
        assert_eq!(m.morph_id_column, "commentable_id");
    }

    #[test]
    fn test_is_valid_sql_identifier_accepts_valid() {
        // 合法标识符
        assert!(is_valid_sql_identifier("users"));
        assert!(is_valid_sql_identifier("UserProfiles"));
        assert!(is_valid_sql_identifier("_private"));
        assert!(is_valid_sql_identifier("table_123"));
        assert!(is_valid_sql_identifier("a"));
    }

    #[test]
    fn test_is_valid_sql_identifier_rejects_invalid() {
        //        assert!(!is_valid_sql_identifier(""));
        // 数字开头
        assert!(!is_valid_sql_identifier("1table"));
        // 包含特殊字符(SQL 注入尝试)
        assert!(!is_valid_sql_identifier("users; DROP TABLE users;--"));
        assert!(!is_valid_sql_identifier("users' OR '1'='1"));
        assert!(!is_valid_sql_identifier("users--"));
        assert!(!is_valid_sql_identifier("users /* comment */"));
        // 包含空格
        assert!(!is_valid_sql_identifier("users table"));
        // 包含点(schema.table 形式)
        assert!(!is_valid_sql_identifier("public.users"));
        // 超长(>64 字符)
        assert!(!is_valid_sql_identifier(&"a".repeat(65)));
        // 中文字符
        assert!(!is_valid_sql_identifier("用户表"));
    }

    #[test]
    fn test_is_valid_sql_identifier_boundary() {
        // 恰好 64 字符(合法)
        assert!(is_valid_sql_identifier(&"a".repeat(64)));
        // 恰好 65 字符(非法)
        assert!(!is_valid_sql_identifier(&"a".repeat(65)));
        // 单个下划线
        assert!(is_valid_sql_identifier("_"));
        // 单个字母
        assert!(is_valid_sql_identifier("x"));
    }

    #[test]
    fn test_relation_enum_has_morph_variants() {
        let morph_many = Relation::MorphMany(MorphMany {
            child_model: "comments".to_string(),
            morph_type_column: "commentable_type".to_string(),
            morph_id_column: "commentable_id".to_string(),
            morph_type_value: "User".to_string(),
        });
        if let Relation::MorphMany(ref m) = morph_many {
            assert_eq!(m.morph_type_value, "User");
        } else {
            panic!("Expected MorphMany");
        }

        let morph_to = Relation::MorphTo(MorphTo {
            morph_type_column: "commentable_type".to_string(),
            morph_id_column: "commentable_id".to_string(),
        });
        if let Relation::MorphTo(ref m) = morph_to {
            assert_eq!(m.morph_type_column, "commentable_type");
        } else {
            panic!("Expected MorphTo");
        }
    }

    #[tokio::test]
    async fn test_active_record_with_morph_many() {
        // Post → comments (morph_type='Post')
        let post = make_user(); // 复用 UserModel 但修改 morph_type_value 需要单独配置
        let mut conn = MockConnection {
            query_results: {
                let mut m = HashMap::new();
                // UserModel 中配置的 MorphMany morph_type_value = "User"
                m.insert(
                    "SELECT * FROM comments WHERE commentable_type = 'User' AND commentable_id = 1"
                        .to_string(),
                    vec![
                        make_comment_row(1, "User", 1, "Nice user"),
                        make_comment_row(2, "User", 1, "Cool"),
                    ],
                );
                m
            },
        };

        let user = post.with("comments").load(&mut conn).await.unwrap();
        let data = user.get_relation("comments");
        assert!(data.is_some());
        if let Some(Value::Array(items)) = data {
            assert_eq!(items.len(), 2);
        } else {
            panic!("Expected Array");
        }
    }

    #[tokio::test]
    async fn test_active_record_with_morph_to() {
        let comment = make_comment();
        let mut conn = MockConnection {
            query_results: {
                let mut m = HashMap::new();
                // CommentModel.commentable 路由到 users 表
                m.insert(
                    "SELECT * FROM users WHERE id = 1".to_string(),
                    vec![make_team_row(1, "Alice")], // 复用 make_team_row 构造一个 id+name 行
                );
                m
            },
        };

        let comment = comment.with("commentable").load(&mut conn).await.unwrap();
        let data = comment.get_relation("commentable");
        assert!(data.is_some());
        if let Some(Value::Array(items)) = data {
            assert_eq!(items.len(), 1);
        }
    }

    #[tokio::test]
    async fn test_active_record_morph_to_empty_type() {
        // morph_type 为空时,应返回空数组而非查询错误
        let mut comment = make_comment();
        comment.commentable_type = String::new(); // 空类型
        let mut conn = MockConnection {
            query_results: HashMap::new(),
        };

        let comment = comment.with("commentable").load(&mut conn).await.unwrap();
        let data = comment.get_relation("commentable").unwrap();
        match data {
            Value::Array(items) => assert!(items.is_empty()),
            _ => panic!("Expected empty Array"),
        }
    }

    #[tokio::test]
    async fn test_relation_access_morph_many() {
        let mut conn = MockConnection {
            query_results: {
                let mut m = HashMap::new();
                m.insert(
                    "SELECT * FROM comments WHERE commentable_type = 'User' AND commentable_id = 1"
                        .to_string(),
                    vec![make_comment_row(10, "User", 1, "via morph many")],
                );
                m
            },
        };

        let user = make_user().with("comments").load(&mut conn).await.unwrap();
        let comments = user.get_morph_many("comments").unwrap();
        assert_eq!(comments.len(), 1);
        assert_eq!(
            comments[0].get("body").unwrap(),
            &Value::String("via morph many".to_string())
        );
    }

    #[tokio::test]
    async fn test_relation_access_morph_to() {
        let comment = make_comment();
        let mut conn = MockConnection {
            query_results: {
                let mut m = HashMap::new();
                m.insert(
                    "SELECT * FROM users WHERE id = 1".to_string(),
                    vec![make_team_row(1, "Alice")],
                );
                m
            },
        };

        let comment = comment.with("commentable").load(&mut conn).await.unwrap();
        let parent = comment.get_morph_to("commentable").unwrap();
        assert!(parent.is_some());
        assert_eq!(
            parent.unwrap().get("name").unwrap(),
            &Value::String("Alice".to_string())
        );
    }

    #[test]
    fn test_morph_to_not_loaded() {
        let comment = make_comment();
        let result = comment.get_morph_to("commentable");
        assert!(result.is_err());
        match result {
            Err(RelationError::NotLoaded(name)) => assert_eq!(name, "commentable"),
            _ => panic!("Expected NotLoaded"),
        }
    }

    #[test]
    fn test_morph_many_not_loaded() {
        let user = make_user();
        let result = user.get_morph_many("comments");
        assert!(result.is_err());
    }

    /// L-1 测试:escape_sql_value 转义完整性
    #[test]
    fn test_l1_escape_sql_value_special_chars() {
        // 单引号 → ''
        assert_eq!(escape_sql_value("it's"), "it''s");
        // 反斜杠 → \\
        assert_eq!(escape_sql_value("a\\b"), "a\\\\b");
        // NUL → \0
        assert_eq!(escape_sql_value("a\0b"), "a\\0b");
        // 换行 → \n
        assert_eq!(escape_sql_value("a\nb"), "a\\nb");
        // 回车 → \r
        assert_eq!(escape_sql_value("a\rb"), "a\\rb");
        // Ctrl+Z (0x1a) → \Z
        assert_eq!(escape_sql_value("a\x1ab"), "a\\Zb");
        // 双引号 → \"
        assert_eq!(escape_sql_value("a\"b"), "a\\\"b");
        // 退格 (0x08) → \b
        assert_eq!(escape_sql_value("a\x08b"), "a\\bb");
        // 无特殊字符:保持原样
        assert_eq!(escape_sql_value("hello world"), "hello world");
        // 混合
        assert_eq!(
            escape_sql_value("it's a \\test\0\n\r\""),
            "it''s a \\\\test\\0\\n\\r\\\""
        );
    }

    /// L-1 测试:pk_to_sql_string 字符串值安全转义
    #[test]
    fn test_l1_pk_to_sql_string_with_special_chars() {
        // 数字主键:不加引号
        let pk_i64 = 42i64;
        assert_eq!(pk_to_sql_string(&pk_i64), "42");
        // 字符串主键:加引号 + 转义
        let pk_str = "it's a \"test\\";
        let result = pk_to_sql_string(&pk_str);
        assert_eq!(result, "'it''s a \\\"test\\\\'");
    }

    /// L-1 测试:value_to_sql_string 始终加引号并转义
    #[test]
    fn test_l1_value_to_sql_string_with_special_chars() {
        assert_eq!(value_to_sql_string("hello'world"), "'hello''world'");
        assert_eq!(value_to_sql_string("back\\slash"), "'back\\\\slash'");
        assert_eq!(value_to_sql_string("nul\0byte"), "'nul\\0byte'");
    }
}