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
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
//! Repository Pattern 仓储模式
//!
//! 对应文档 6.8 节改进项 37(Repository Pattern 仓储模式)。
//!
//! # 核心概念
//!
//! - **Repository trait**:统一的仓储接口,定义 CRUD + 分页 + 条件查询
//! - **InMemoryRepository**:内存仓储实现(用于测试、原型、无数据库场景)
//! - **WhereCondition / WhereOp**:查询条件
//! - **PageResult**:分页结果
//! - **RepositoryError**:仓储错误
//!
//! # 设计灵感
//!
//! - Doctrine `EntityRepository`
//! - Spring Data JPA `@Repository` / `JpaRepository`
//! - MyBatis-Plus `IService` / `BaseMapper`
//! - Laravel Eloquent `Repository`
//! - DDD(领域驱动设计)的 Repository 模式
//!
//! # 优势
//!
//! 1. **分层解耦**:业务层依赖 Repository 接口,不直接依赖 Model 静态方法
//! 2. **可替换性**:同一接口可有 InMemory / SQL / NoSQL 等多种实现
//! 3. **可测试**:单元测试用 InMemoryRepository;生产环境请直接使用 QueryBuilder + Connection
//! 4. **统一 API**:CRUD + 分页 + 条件查询接口统一
//!
//! # 重要说明
//!
//! 本模块**仅提供 InMemoryRepository**(内存实现),**不提供 SqlRepository**。
//! 如需基于 SQL 的仓储实现,请直接使用 `QueryBuilder` 生成 SQL 并通过
//! `Pool::acquire()` 获取连接后执行。InMemoryRepository 主要用于单元测试与
//! 业务逻辑原型验证,不执行任何真实 SQL。
//!
//! # 使用示例
//!
//! ```
//! use sz_orm_core::repository::{
//!     InMemoryRepository, Repository, WhereCondition, WhereOp, PageResult,
//! };
//! use sz_orm_core::Value;
//! use std::collections::HashMap;
//!
//! // 假设 User 是 Model 的实现
//! // let repo = InMemoryRepository::<User>::new();
//! // let user = repo.find_by_id(1)?;
//! // let adults = repo.find_by(&[WhereCondition::new("age", WhereOp::Ge, Value::I64(18))])?;
//! ```

use crate::Value;
use std::fmt::Debug;
use std::sync::RwLock;

// ============================================================================
// WhereCondition — 查询条件
// ============================================================================

/// 查询操作符
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WhereOp {
    /// `=`
    Eq,
    /// `!=`
    Ne,
    /// `>`
    Gt,
    /// `>=`
    Ge,
    /// `<`
    Lt,
    /// `<=`
    Le,
    /// `LIKE`
    Like,
    /// `IN`
    In,
    /// `NOT IN`
    NotIn,
    /// `IS NULL`
    IsNull,
    /// `IS NOT NULL`
    IsNotNull,
    /// `BETWEEN`
    Between,
}

impl WhereOp {
    /// 操作符名称
    pub fn name(&self) -> &'static str {
        match self {
            WhereOp::Eq => "eq",
            WhereOp::Ne => "ne",
            WhereOp::Gt => "gt",
            WhereOp::Ge => "ge",
            WhereOp::Lt => "lt",
            WhereOp::Le => "le",
            WhereOp::Like => "like",
            WhereOp::In => "in",
            WhereOp::NotIn => "not_in",
            WhereOp::IsNull => "is_null",
            WhereOp::IsNotNull => "is_not_null",
            WhereOp::Between => "between",
        }
    }
}

/// 查询条件
#[derive(Debug, Clone)]
pub struct WhereCondition {
    pub field: String,
    pub op: WhereOp,
    pub value: Value,
    /// For Between / In / NotIn,副值列表
    pub extra_values: Vec<Value>,
}

impl WhereCondition {
    /// 创建单值条件(Eq/Ne/Gt/Ge/Lt/Le/Like)
    pub fn new(field: impl Into<String>, op: WhereOp, value: Value) -> Self {
        Self {
            field: field.into(),
            op,
            value,
            extra_values: Vec::new(),
        }
    }

    /// 创建 IsNull / IsNotNull 条件
    pub fn null_check(field: impl Into<String>, op: WhereOp) -> Self {
        Self {
            field: field.into(),
            op,
            value: Value::Null,
            extra_values: Vec::new(),
        }
    }

    /// 创建 In / NotIn 条件
    pub fn in_op(field: impl Into<String>, op: WhereOp, values: Vec<Value>) -> Self {
        Self {
            field: field.into(),
            op,
            value: Value::Null,
            extra_values: values,
        }
    }

    /// 创建 Between 条件
    pub fn between(field: impl Into<String>, low: Value, high: Value) -> Self {
        Self {
            field: field.into(),
            op: WhereOp::Between,
            value: low,
            extra_values: vec![high],
        }
    }
}

// ============================================================================
// PageResult — 分页结果
// ============================================================================

/// 分页结果
#[derive(Debug, Clone)]
pub struct PageResult<T> {
    pub items: Vec<T>,
    pub total: u64,
    pub page: u64,
    pub page_size: u64,
}

impl<T> PageResult<T> {
    /// 创建分页结果
    pub fn new(items: Vec<T>, total: u64, page: u64, page_size: u64) -> Self {
        Self {
            items,
            total,
            page,
            page_size,
        }
    }

    /// 总页数
    pub fn total_pages(&self) -> u64 {
        if self.page_size == 0 {
            return 0;
        }
        self.total.div_ceil(self.page_size)
    }

    /// 是否有下一页
    pub fn has_next(&self) -> bool {
        self.page < self.total_pages()
    }

    /// 是否有上一页
    pub fn has_prev(&self) -> bool {
        self.page > 1
    }

    /// 是否为空
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// 当前页条数
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// 映射为其他类型
    pub fn map<U, F: Fn(T) -> U>(self, f: F) -> PageResult<U> {
        PageResult {
            items: self.items.into_iter().map(f).collect(),
            total: self.total,
            page: self.page,
            page_size: self.page_size,
        }
    }
}

// ============================================================================
// BatchUpdateResult — 批量更新结果(S-1:SeaORM 对标短板补全)
// ============================================================================

/// 批量更新结果
///
/// 由 [`Repository::batch_update`](Repository::batch_update) 返回,
/// 区分成功更新的实体与因主键不存在而被跳过的实体数量。
///
/// # 字段
///
/// - `updated`:成功更新的实体列表(按主键匹配命中并完成 UPDATE)
/// - `skipped`:主键不存在而被跳过的实体数量
///
/// # 设计动机
///
/// SeaORM 的 `update_many` 不区分"存在"与"不存在",只返回受影响行数。
/// 本结构明确区分两者,便于调用方感知部分失败(如批量同步外部数据时
/// 部分记录已被删除)并采取补偿措施(记录日志、重试插入等)。
#[derive(Debug, Clone)]
pub struct BatchUpdateResult<E> {
    /// 成功更新的实体列表
    pub updated: Vec<E>,
    /// 主键不存在而被跳过的实体数量
    pub skipped: usize,
}

impl<E> BatchUpdateResult<E> {
    /// 创建批量更新结果
    pub fn new(updated: Vec<E>, skipped: usize) -> Self {
        Self { updated, skipped }
    }

    /// 成功更新数量
    pub fn updated_count(&self) -> usize {
        self.updated.len()
    }

    /// 是否有跳过的实体
    pub fn has_skipped(&self) -> bool {
        self.skipped > 0
    }

    /// 是否全部成功(无跳过)
    pub fn all_updated(&self) -> bool {
        self.skipped == 0
    }

    /// 总计处理数量(已更新 + 跳过)
    pub fn total(&self) -> usize {
        self.updated.len() + self.skipped
    }

    /// 映射已更新实体为其他类型(保留 skipped 计数)
    pub fn map<U, F: Fn(E) -> U>(self, f: F) -> BatchUpdateResult<U> {
        BatchUpdateResult {
            updated: self.updated.into_iter().map(f).collect(),
            skipped: self.skipped,
        }
    }
}

impl<E> Default for BatchUpdateResult<E> {
    fn default() -> Self {
        Self {
            updated: Vec::new(),
            skipped: 0,
        }
    }
}

// ============================================================================
// RepositoryError — 错误类型
// ============================================================================

/// `InMemoryRepository` 分页操作的安全扫描上限。
///
/// `InMemoryRepository` 的分页实现会将匹配行全部加载到内存后再切片,
/// 当表行数过大时会导致 OOM。此常量定义了允许加载的最大行数;超过此
/// 值时 `paginate` / `paginate_by` 直接返回 `RepositoryError::TooManyRows`。
///
/// 生产环境请使用 `QueryBuilder` + `limit`/`offset` 将分页下推到数据库层,
/// 不受此限制影响。
pub const REPOSITORY_SCAN_LIMIT: usize = 100_000;

/// Repository 错误
#[derive(Debug, Clone, PartialEq)]
pub enum RepositoryError {
    /// 实体未找到
    NotFound,
    /// 数据库错误
    DatabaseError(String),
    /// 实体无效(如缺主键)
    InvalidEntity(String),
    /// 其他错误
    Other(String),
    /// 扫描行数超过安全上限(防止内存型分页 OOM)
    ///
    /// `InMemoryRepository` 的 `paginate` / `paginate_by` 会将全表加载到内存
    /// 后再切片。当表行数超过 `REPOSITORY_SCAN_LIMIT`(默认 100_000)时,
    /// 返回此错误而非继续加载,避免大表直接 OOM。
    ///
    /// 生产环境请使用 `QueryBuilder` + `limit`/`offset` 将分页下推到数据库层。
    TooManyRows { actual: usize, limit: usize },
}

impl std::fmt::Display for RepositoryError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RepositoryError::NotFound => write!(f, "entity not found"),
            RepositoryError::DatabaseError(msg) => write!(f, "database error: {}", msg),
            RepositoryError::InvalidEntity(msg) => write!(f, "invalid entity: {}", msg),
            RepositoryError::Other(msg) => write!(f, "repository error: {}", msg),
            RepositoryError::TooManyRows { actual, limit } => write!(
                f,
                "scan result exceeds safety limit: {} rows (limit: {}); \
                 use QueryBuilder + limit/offset to push pagination to the database",
                actual, limit
            ),
        }
    }
}

impl std::error::Error for RepositoryError {}

/// Repository 结果类型
pub type RepositoryResult<T> = Result<T, RepositoryError>;

// ============================================================================
// Repository trait — 仓储接口
// ============================================================================

/// 仓储接口(generic over Model-like entity E, primary key K)
///
/// E 不必是 `Model` trait 实现,仅需满足存储基本要求。
/// 这样设计允许存储任意结构(DTO、聚合、领域实体等)。
pub trait Repository<E>: Send + Sync {
    /// 主键类型
    type Key: Clone + Debug + PartialEq + Send + Sync;

    /// 提取实体的主键
    fn key_of(&self, entity: &E) -> Self::Key;

    /// 按主键查找
    fn find_by_id(&self, key: &Self::Key) -> RepositoryResult<Option<E>>;

    /// 查询所有
    fn find_all(&self) -> RepositoryResult<Vec<E>>;

    /// 按条件查询
    fn find_by(&self, conditions: &[WhereCondition]) -> RepositoryResult<Vec<E>>;

    /// 按条件查询单条
    fn find_one_by(&self, conditions: &[WhereCondition]) -> RepositoryResult<Option<E>> {
        let mut items = self.find_by(conditions)?;
        if items.is_empty() {
            Ok(None)
        } else {
            Ok(Some(items.remove(0)))
        }
    }

    /// 保存(INSERT 或 UPDATE)
    ///
    /// 返回保存后的实体(可能是克隆,主键可能被填充)
    fn save(&self, entity: E) -> RepositoryResult<E>;

    /// 批量保存
    fn save_many(&self, entities: Vec<E>) -> RepositoryResult<Vec<E>> {
        let mut saved = Vec::with_capacity(entities.len());
        for e in entities {
            saved.push(self.save(e)?);
        }
        Ok(saved)
    }

    /// 批量更新(S-1:SeaORM 对标短板补全)
    ///
    /// 仅更新已存在的实体(按主键匹配),不存在的实体跳过并计入 `skipped`。
    /// 与 [`save_many`](Self::save_many) 的区别:`save_many` 是 upsert(存在则更新,不存在则插入),
    /// `batch_update` 是纯更新(不存在则跳过)。
    ///
    /// 默认实现为逐条调用 [`find_by_id`](Self::find_by_id) + [`save`](Self::save),
    /// 具体实现可重写为真正的批量 UPDATE SQL(如 `UPDATE ... SET ... WHERE id IN (...)`)。
    ///
    /// # 参数
    ///
    /// - `entities`:待更新的实体列表(主键必须已填充)
    ///
    /// # 返回
    ///
    /// - `updated`:成功更新的实体列表
    /// - `skipped`:主键不存在而被跳过的实体数量
    fn batch_update(&self, entities: Vec<E>) -> RepositoryResult<BatchUpdateResult<E>> {
        let mut updated = Vec::with_capacity(entities.len());
        let mut skipped = 0usize;
        for e in entities {
            let key = self.key_of(&e);
            if self.find_by_id(&key)?.is_some() {
                updated.push(self.save(e)?);
            } else {
                skipped += 1;
            }
        }
        Ok(BatchUpdateResult { updated, skipped })
    }

    /// 按主键删除
    fn delete(&self, key: &Self::Key) -> RepositoryResult<usize>;

    /// 按条件删除
    fn delete_by(&self, conditions: &[WhereCondition]) -> RepositoryResult<usize> {
        let items = self.find_by(conditions)?;
        let mut count = 0;
        for item in items {
            let key = self.key_of(&item);
            count += self.delete(&key)?;
        }
        Ok(count)
    }

    /// 总数
    fn count(&self) -> RepositoryResult<u64>;

    /// 按条件计数
    fn count_by(&self, conditions: &[WhereCondition]) -> RepositoryResult<u64> {
        let items = self.find_by(conditions)?;
        Ok(items.len() as u64)
    }

    /// 主键是否存在
    fn exists(&self, key: &Self::Key) -> RepositoryResult<bool> {
        Ok(self.find_by_id(key)?.is_some())
    }

    /// 分页查询
    ///
    /// # 安全限制
    ///
    /// 本实现在内存中加载全表后切片。调用前会先检查总行数,若超过
    /// [`REPOSITORY_SCAN_LIMIT`] 则返回 [`RepositoryError::TooManyRows`],
    /// 避免大表 OOM。生产环境请使用 `QueryBuilder` + `limit`/`offset`。
    fn paginate(&self, page: u64, page_size: u64) -> RepositoryResult<PageResult<E>>
    where
        E: Clone,
    {
        let total = self.count()? as usize;
        if total > REPOSITORY_SCAN_LIMIT {
            return Err(RepositoryError::TooManyRows {
                actual: total,
                limit: REPOSITORY_SCAN_LIMIT,
            });
        }
        let all = self.find_all()?;
        let start = ((page.saturating_sub(1)) * page_size) as usize;
        let end = (start + page_size as usize).min(all.len());

        let items = if start < all.len() {
            all[start..end].to_vec()
        } else {
            Vec::new()
        };

        Ok(PageResult::new(items, total as u64, page, page_size))
    }

    /// 按条件分页查询
    ///
    /// # 安全限制
    ///
    /// 同 [`paginate`]:匹配行数超过 [`REPOSITORY_SCAN_LIMIT`] 时返回
    /// [`RepositoryError::TooManyRows`]。
    fn paginate_by(
        &self,
        conditions: &[WhereCondition],
        page: u64,
        page_size: u64,
    ) -> RepositoryResult<PageResult<E>>
    where
        E: Clone,
    {
        let total = self.count_by(conditions)? as usize;
        if total > REPOSITORY_SCAN_LIMIT {
            return Err(RepositoryError::TooManyRows {
                actual: total,
                limit: REPOSITORY_SCAN_LIMIT,
            });
        }
        let all = self.find_by(conditions)?;
        let start = ((page.saturating_sub(1)) * page_size) as usize;
        let end = (start + page_size as usize).min(all.len());

        let items = if start < all.len() {
            all[start..end].to_vec()
        } else {
            Vec::new()
        };

        Ok(PageResult::new(items, total as u64, page, page_size))
    }

    /// 按 AND 条件查询,并对结果应用额外的 OR 过滤组
    ///
    /// 语义:`WHERE (and1 AND and2 AND ...) AND (or1_1 OR or1_2 OR ...)`
    ///
    /// 用于多字段 keyword LIKE 搜索等场景(对齐 PHP ThinkPHP
    /// `where('field1|field2|field3','like','%kw%')` 多字段 OR LIKE 语法)。
    ///
    /// # 默认实现
    ///
    /// 基于 `find_by` + 内存 OR 过滤;SQL 后端实现可重写以将 OR 下推到 SQL,
    /// 避免 `SELECT ... WHERE app_id=?` 全表拉取后再内存过滤的性能问题。
    ///
    /// # 参数
    ///
    /// - `and`:AND 关系的条件列表(同 `find_by`)
    /// - `or_filter`:OR 关系的条件列表,对 `and` 结果做二次过滤
    ///
    /// # 示例
    ///
    /// ```
    /// use sz_orm_core::repository::{Repository, WhereCondition, WhereOp};
    /// use sz_orm_core::Value;
    /// # use sz_orm_core::repository::InMemoryRepository;
    /// # fn example<E: sz_orm_core::repository::EntityAttributes + Clone + Send + Sync + 'static>(repo: &dyn Repository<E, Key = Value>) {
    /// let and = vec![
    ///     WhereCondition::new("is_delete", WhereOp::Eq, Value::I64(0)),
    ///     WhereCondition::new("app_id", WhereOp::Eq, Value::I64(1)),
    /// ];
    /// let or = vec![
    ///     WhereCondition::new("name", WhereOp::Like, Value::String("%kw%".into())),
    ///     WhereCondition::new("addr", WhereOp::Like, Value::String("%kw%".into())),
    /// ];
    /// let items = repo.find_by_with_or_filter(&and, &or).unwrap();
    /// # }
    /// ```
    fn find_by_with_or_filter(
        &self,
        and: &[WhereCondition],
        or_filter: &[WhereCondition],
    ) -> RepositoryResult<Vec<E>>
    where
        E: Clone + EntityAttributes,
    {
        let items = self.find_by(and)?;
        if or_filter.is_empty() {
            return Ok(items);
        }
        Ok(items
            .into_iter()
            .filter(|e| {
                or_filter.iter().any(|c| {
                    let attr = e.get_attribute(&c.field);
                    match (attr, c.op) {
                        (None, WhereOp::IsNull) => true,
                        (None, _) => false,
                        (Some(v), _) => value_matches(&v, c.op, &c.value, &c.extra_values),
                    }
                })
            })
            .collect())
    }
}

// ============================================================================
// InMemoryRepository — 内存仓储实现
// ============================================================================

/// 内存仓储实现
///
/// 使用 `Vec<E>` 存储实体,主键通过 `key_of` 提取。
/// 适合单元测试、原型开发、无数据库场景。
pub struct InMemoryRepository<E: Clone + Send + Sync + 'static> {
    storage: RwLock<Vec<E>>,
}

impl<E: Clone + Send + Sync + 'static> InMemoryRepository<E> {
    /// 创建空仓储
    pub fn new() -> Self {
        Self {
            storage: RwLock::new(Vec::new()),
        }
    }

    /// 从已有集合创建
    pub fn from_vec(items: Vec<E>) -> Self {
        Self {
            storage: RwLock::new(items),
        }
    }

    /// 当前存储条数
    pub fn len(&self) -> usize {
        match self.storage.read() {
            Ok(storage) => storage.len(),
            Err(_) => 0,
        }
    }

    /// 是否为空
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// 清空
    pub fn clear(&self) {
        if let Ok(mut storage) = self.storage.write() {
            storage.clear();
        }
    }
}

impl<E: Clone + Send + Sync + 'static> Default for InMemoryRepository<E> {
    fn default() -> Self {
        Self::new()
    }
}

/// 值比较辅助函数(支持基本类型 + Value 比较)
fn value_matches(value: &Value, op: WhereOp, target: &Value, extras: &[Value]) -> bool {
    use Value::*;
    match op {
        WhereOp::Eq => value == target,
        WhereOp::Ne => value != target,
        WhereOp::Gt => match (value, target) {
            (I64(a), I64(b)) => a > b,
            (F64(a), F64(b)) => a > b,
            (F64(a), I64(b)) => a > &(*b as f64),
            (I64(a), F64(b)) => a > &(*b as i64),
            (String(a), String(b)) => a > b,
            _ => false,
        },
        WhereOp::Ge => match (value, target) {
            (I64(a), I64(b)) => a >= b,
            (F64(a), F64(b)) => a >= b,
            (String(a), String(b)) => a >= b,
            _ => false,
        },
        WhereOp::Lt => match (value, target) {
            (I64(a), I64(b)) => a < b,
            (F64(a), F64(b)) => a < b,
            (String(a), String(b)) => a < b,
            _ => false,
        },
        WhereOp::Le => match (value, target) {
            (I64(a), I64(b)) => a <= b,
            (F64(a), F64(b)) => a <= b,
            (String(a), String(b)) => a <= b,
            _ => false,
        },
        WhereOp::Like => match (value, target) {
            (String(a), String(b)) => {
                // 简化 LIKE:将 % 转换为 .*,其他字符转义
                // 大小写不敏感(对齐 MySQL utf8mb4_general_ci / utf8mb4_unicode_ci 默认 collation)
                let pattern = b.to_lowercase().replace('%', ".*").replace('_', ".");
                let full_pattern = format!("^{}$", pattern);
                if let Ok(re) = simple_regex::compile(&full_pattern) {
                    re.is_match(&a.to_lowercase())
                } else {
                    false
                }
            }
            _ => false,
        },
        WhereOp::In => extras.iter().any(|v| v == value),
        WhereOp::NotIn => !extras.iter().any(|v| v == value),
        WhereOp::IsNull => matches!(value, Null),
        WhereOp::IsNotNull => !matches!(value, Null),
        WhereOp::Between => {
            if extras.is_empty() {
                return false;
            }
            let low = target;
            let high = &extras[0];
            // value >= low AND value <= high
            value_matches(value, WhereOp::Ge, low, &[])
                && value_matches(value, WhereOp::Le, high, &[])
        }
    }
}

/// 实体属性提取 trait(用户为实体实现此 trait 以支持 find_by)
pub trait EntityAttributes: Send + Sync {
    /// 按字段名获取属性值
    fn get_attribute(&self, field: &str) -> Option<Value>;
}

/// InMemoryRepository 的 EntityAttributes-based 实现
impl<E: Clone + Send + Sync + 'static + EntityAttributes> Repository<E> for InMemoryRepository<E> {
    type Key = Value;

    fn key_of(&self, entity: &E) -> Self::Key {
        entity.get_attribute("id").unwrap_or(Value::Null)
    }

    fn find_by_id(&self, key: &Self::Key) -> RepositoryResult<Option<E>> {
        let storage = match self.storage.read() {
            Ok(g) => g,
            Err(_) => return Ok(None),
        };
        Ok(storage.iter().find(|e| self.key_of(e) == *key).cloned())
    }

    fn find_all(&self) -> RepositoryResult<Vec<E>> {
        let storage = match self.storage.read() {
            Ok(g) => g,
            Err(_) => return Ok(Vec::new()),
        };
        Ok(storage.clone())
    }

    fn find_by(&self, conditions: &[WhereCondition]) -> RepositoryResult<Vec<E>> {
        let storage = match self.storage.read() {
            Ok(g) => g,
            Err(_) => return Ok(Vec::new()),
        };
        let result: Vec<E> = storage
            .iter()
            .filter(|e| {
                conditions.iter().all(|c| {
                    let attr = e.get_attribute(&c.field);
                    match (attr, c.op) {
                        (None, WhereOp::IsNull) => true,
                        (None, _) => false,
                        (Some(v), _) => value_matches(&v, c.op, &c.value, &c.extra_values),
                    }
                })
            })
            .cloned()
            .collect();
        Ok(result)
    }

    fn save(&self, mut entity: E) -> RepositoryResult<E> {
        let mut storage = match self.storage.write() {
            Ok(g) => g,
            Err(_) => return Ok(entity),
        };
        let key = self.key_of(&entity);

        // 查找是否已存在
        let existing_idx = storage.iter().position(|e| self.key_of(e) == key);

        match existing_idx {
            Some(idx) => {
                storage[idx] = entity.clone();
            }
            None => {
                storage.push(entity.clone());
            }
        }
        // 注意:entity 可能被修改(如自增主键),这里返回原值
        let _ = &mut entity; // 标记 mut 以符合签名
        Ok(entity)
    }

    fn delete(&self, key: &Self::Key) -> RepositoryResult<usize> {
        let mut storage = match self.storage.write() {
            Ok(g) => g,
            Err(_) => return Ok(0),
        };
        let before = storage.len();
        storage.retain(|e| self.key_of(e) != *key);
        Ok(before - storage.len())
    }

    fn count(&self) -> RepositoryResult<u64> {
        Ok(self.len() as u64)
    }
}

// ============================================================================
// simple_regex — 极简 LIKE 模式匹配(避免引入正则依赖)
// ============================================================================

mod simple_regex {
    /// 极简正则编译器:仅支持 `.*`、`^`、`$`、字面字符
    pub struct Regex {
        patterns: Vec<Pattern>,
    }

    enum Pattern {
        AnyChars,      // .*(贪婪匹配任意字符)
        Literal(char), // 字面字符
        Start,         // ^
        End,           // $
    }

    pub fn compile(pattern: &str) -> Result<Regex, String> {
        let mut patterns = Vec::new();
        let chars: Vec<char> = pattern.chars().collect();
        let mut i = 0;
        while i < chars.len() {
            match chars[i] {
                '^' => {
                    patterns.push(Pattern::Start);
                    i += 1;
                }
                '$' => {
                    patterns.push(Pattern::End);
                    i += 1;
                }
                '.' if i + 1 < chars.len() && chars[i + 1] == '*' => {
                    patterns.push(Pattern::AnyChars);
                    i += 2;
                }
                c => {
                    patterns.push(Pattern::Literal(c));
                    i += 1;
                }
            }
        }
        Ok(Regex { patterns })
    }

    impl Regex {
        pub fn is_match(&self, text: &str) -> bool {
            self.match_from(text, 0, 0)
        }

        fn match_from(&self, text: &str, text_idx: usize, pat_idx: usize) -> bool {
            let chars: Vec<char> = text.chars().collect();
            if pat_idx >= self.patterns.len() {
                return text_idx == chars.len();
            }
            match &self.patterns[pat_idx] {
                Pattern::Start => self.match_from(text, 0, pat_idx + 1),
                Pattern::End => text_idx == chars.len(),
                Pattern::Literal(c) => {
                    if text_idx < chars.len() && chars[text_idx] == *c {
                        self.match_from(text, text_idx + 1, pat_idx + 1)
                    } else {
                        false
                    }
                }
                Pattern::AnyChars => {
                    // 尝试匹配 0 到 len 个字符
                    for skip in 0..=(chars.len() - text_idx) {
                        if self.match_from(text, text_idx + skip, pat_idx + 1) {
                            return true;
                        }
                    }
                    false
                }
            }
        }
    }
}

// ============================================================================
// GenericKeyRepository — 支持任意 Key 类型的内存仓储
// ============================================================================

/// 通用 Key 提取 trait(用户为实体实现此 trait 以支持任意 Key 类型)
pub trait EntityKey<K>: Send + Sync {
    /// 提取主键
    fn key(&self) -> K;
}

/// 通用 Key 内存仓储
pub struct GenericKeyRepository<E, K>
where
    E: Clone + Send + Sync + 'static,
    K: Clone + Debug + PartialEq + Send + Sync + 'static,
{
    storage: RwLock<Vec<E>>,
    _phantom: std::marker::PhantomData<K>,
}

impl<E, K> GenericKeyRepository<E, K>
where
    E: Clone + Send + Sync + 'static,
    K: Clone + Debug + PartialEq + Send + Sync + 'static,
{
    pub fn new() -> Self {
        Self {
            storage: RwLock::new(Vec::new()),
            _phantom: std::marker::PhantomData,
        }
    }

    pub fn from_vec(items: Vec<E>) -> Self {
        Self {
            storage: RwLock::new(items),
            _phantom: std::marker::PhantomData,
        }
    }

    pub fn len(&self) -> usize {
        match self.storage.read() {
            Ok(g) => g.len(),
            Err(_) => 0,
        }
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn clear(&self) {
        if let Ok(mut storage) = self.storage.write() {
            storage.clear();
        }
    }
}

impl<E, K> Default for GenericKeyRepository<E, K>
where
    E: Clone + Send + Sync + 'static,
    K: Clone + Debug + PartialEq + Send + Sync + 'static,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<E, K> Repository<E> for GenericKeyRepository<E, K>
where
    E: Clone + Send + Sync + 'static + EntityKey<K> + EntityAttributes,
    K: Clone + Debug + PartialEq + Send + Sync + 'static,
{
    type Key = K;

    fn key_of(&self, entity: &E) -> Self::Key {
        entity.key()
    }

    fn find_by_id(&self, key: &Self::Key) -> RepositoryResult<Option<E>> {
        let storage = match self.storage.read() {
            Ok(g) => g,
            Err(_) => return Ok(None),
        };
        Ok(storage.iter().find(|e| &e.key() == key).cloned())
    }

    fn find_all(&self) -> RepositoryResult<Vec<E>> {
        let storage = match self.storage.read() {
            Ok(g) => g,
            Err(_) => return Ok(Vec::new()),
        };
        Ok(storage.clone())
    }

    fn find_by(&self, conditions: &[WhereCondition]) -> RepositoryResult<Vec<E>> {
        let storage = match self.storage.read() {
            Ok(g) => g,
            Err(_) => return Ok(Vec::new()),
        };
        let result: Vec<E> = storage
            .iter()
            .filter(|e| {
                conditions.iter().all(|c| {
                    let attr = e.get_attribute(&c.field);
                    match (attr, c.op) {
                        (None, WhereOp::IsNull) => true,
                        (None, _) => false,
                        (Some(v), _) => value_matches(&v, c.op, &c.value, &c.extra_values),
                    }
                })
            })
            .cloned()
            .collect();
        Ok(result)
    }

    fn save(&self, entity: E) -> RepositoryResult<E> {
        let mut storage = match self.storage.write() {
            Ok(g) => g,
            Err(_) => return Ok(entity),
        };
        let key = entity.key();
        let existing_idx = storage.iter().position(|e| e.key() == key);
        match existing_idx {
            Some(idx) => {
                storage[idx] = entity.clone();
            }
            None => {
                storage.push(entity.clone());
            }
        }
        Ok(entity)
    }

    fn delete(&self, key: &Self::Key) -> RepositoryResult<usize> {
        let mut storage = match self.storage.write() {
            Ok(g) => g,
            Err(_) => return Ok(0),
        };
        let before = storage.len();
        storage.retain(|e| &e.key() != key);
        Ok(before - storage.len())
    }

    fn count(&self) -> RepositoryResult<u64> {
        Ok(self.len() as u64)
    }
}

// ============================================================================
// 单元测试
// ============================================================================

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

    // ===== 测试用实体 =====

    #[derive(Debug, Clone, PartialEq)]
    struct User {
        id: i64,
        name: String,
        age: i64,
        email: String,
    }

    impl User {
        fn new(id: i64, name: &str, age: i64, email: &str) -> Self {
            Self {
                id,
                name: name.to_string(),
                age,
                email: email.to_string(),
            }
        }
    }

    impl EntityAttributes for User {
        fn get_attribute(&self, field: &str) -> Option<Value> {
            match field {
                "id" => Some(Value::I64(self.id)),
                "name" => Some(Value::String(self.name.clone())),
                "age" => Some(Value::I64(self.age)),
                "email" => Some(Value::String(self.email.clone())),
                _ => None,
            }
        }
    }

    impl EntityKey<i64> for User {
        fn key(&self) -> i64 {
            self.id
        }
    }

    // ===== WhereOp / WhereCondition =====

    #[test]
    fn test_where_op_name() {
        assert_eq!(WhereOp::Eq.name(), "eq");
        assert_eq!(WhereOp::Ne.name(), "ne");
        assert_eq!(WhereOp::Gt.name(), "gt");
        assert_eq!(WhereOp::Like.name(), "like");
        assert_eq!(WhereOp::In.name(), "in");
        assert_eq!(WhereOp::IsNull.name(), "is_null");
        assert_eq!(WhereOp::Between.name(), "between");
    }

    #[test]
    fn test_where_condition_new() {
        let c = WhereCondition::new("age", WhereOp::Ge, Value::I64(18));
        assert_eq!(c.field, "age");
        assert_eq!(c.op, WhereOp::Ge);
        assert_eq!(c.value, Value::I64(18));
        assert!(c.extra_values.is_empty());
    }

    #[test]
    fn test_where_condition_null_check() {
        let c = WhereCondition::null_check("deleted_at", WhereOp::IsNull);
        assert_eq!(c.field, "deleted_at");
        assert_eq!(c.op, WhereOp::IsNull);
        assert_eq!(c.value, Value::Null);
    }

    #[test]
    fn test_where_condition_in() {
        let c = WhereCondition::in_op(
            "id",
            WhereOp::In,
            vec![Value::I64(1), Value::I64(2), Value::I64(3)],
        );
        assert_eq!(c.field, "id");
        assert_eq!(c.op, WhereOp::In);
        assert_eq!(c.extra_values.len(), 3);
    }

    #[test]
    fn test_where_condition_between() {
        let c = WhereCondition::between("age", Value::I64(18), Value::I64(30));
        assert_eq!(c.field, "age");
        assert_eq!(c.op, WhereOp::Between);
        assert_eq!(c.value, Value::I64(18));
        assert_eq!(c.extra_values, vec![Value::I64(30)]);
    }

    // ===== PageResult =====

    #[test]
    fn test_page_result_total_pages() {
        let pr = PageResult::new(vec![1, 2, 3], 100, 1, 10);
        assert_eq!(pr.total_pages(), 10);
    }

    #[test]
    fn test_page_result_total_pages_with_remainder() {
        let pr: PageResult<i32> = PageResult::new(vec![], 105, 1, 10);
        assert_eq!(pr.total_pages(), 11);
    }

    #[test]
    fn test_page_result_total_pages_zero_size() {
        let pr: PageResult<i32> = PageResult::new(vec![], 100, 1, 0);
        assert_eq!(pr.total_pages(), 0);
    }

    #[test]
    fn test_page_result_has_next() {
        let pr = PageResult::new(vec![1, 2, 3], 100, 1, 10);
        assert!(pr.has_next());
        assert!(!pr.has_prev());
    }

    #[test]
    fn test_page_result_has_prev() {
        let pr = PageResult::new(vec![1, 2, 3], 100, 5, 10);
        assert!(pr.has_prev());
        assert!(pr.has_next()); // page 5 < total_pages 10
    }

    #[test]
    fn test_page_result_is_empty() {
        let pr: PageResult<i32> = PageResult::new(vec![], 0, 1, 10);
        assert!(pr.is_empty());
        assert_eq!(pr.len(), 0);
    }

    #[test]
    fn test_page_result_map() {
        let pr = PageResult::new(vec![1, 2, 3], 100, 1, 10);
        let mapped = pr.map(|x| x * 2);
        assert_eq!(mapped.items, vec![2, 4, 6]);
        assert_eq!(mapped.total, 100);
    }

    // ===== RepositoryError =====

    #[test]
    fn test_repository_error_display() {
        let e = RepositoryError::NotFound;
        assert_eq!(e.to_string(), "entity not found");

        let e = RepositoryError::DatabaseError("conn refused".to_string());
        assert_eq!(e.to_string(), "database error: conn refused");

        let e = RepositoryError::InvalidEntity("missing id".to_string());
        assert_eq!(e.to_string(), "invalid entity: missing id");

        let e = RepositoryError::Other("custom".to_string());
        assert_eq!(e.to_string(), "repository error: custom");
    }

    #[test]
    fn test_repository_error_eq() {
        assert_eq!(RepositoryError::NotFound, RepositoryError::NotFound);
        assert_ne!(
            RepositoryError::NotFound,
            RepositoryError::Other("x".to_string())
        );
    }

    // ===== InMemoryRepository 基础 =====

    #[test]
    fn test_inmemory_create_empty() {
        let repo = InMemoryRepository::<User>::new();
        assert!(repo.is_empty());
        assert_eq!(repo.len(), 0);
    }

    #[test]
    fn test_inmemory_from_vec() {
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice", 30, "alice@example.com"),
            User::new(2, "Bob", 25, "bob@example.com"),
        ]);
        assert_eq!(repo.len(), 2);
    }

    #[test]
    fn test_inmemory_clear() {
        let repo = InMemoryRepository::from_vec(vec![User::new(1, "Alice", 30, "a@b.com")]);
        assert_eq!(repo.len(), 1);
        repo.clear();
        assert_eq!(repo.len(), 0);
    }

    // ===== Repository trait CRUD =====

    #[test]
    fn test_repo_save_and_find_by_id() {
        let repo = InMemoryRepository::<User>::new();
        let user = User::new(1, "Alice", 30, "alice@example.com");
        let saved = repo.save(user.clone()).unwrap();
        assert_eq!(saved, user);

        let found = repo.find_by_id(&Value::I64(1)).unwrap();
        assert_eq!(found, Some(user));
    }

    #[test]
    fn test_repo_find_by_id_missing() {
        let repo = InMemoryRepository::<User>::new();
        let found = repo.find_by_id(&Value::I64(999)).unwrap();
        assert_eq!(found, None);
    }

    #[test]
    fn test_repo_save_many() {
        let repo = InMemoryRepository::<User>::new();
        let users = vec![
            User::new(1, "Alice", 30, "alice@example.com"),
            User::new(2, "Bob", 25, "bob@example.com"),
            User::new(3, "Carol", 28, "carol@example.com"),
        ];
        let saved = repo.save_many(users.clone()).unwrap();
        assert_eq!(saved.len(), 3);
        assert_eq!(repo.len(), 3);
    }

    // ===== S-1: batch_update 批量更新 =====

    #[test]
    fn test_batch_update_result_new() {
        let result = BatchUpdateResult::new(vec![1, 2, 3], 2);
        assert_eq!(result.updated_count(), 3);
        assert_eq!(result.skipped, 2);
        assert_eq!(result.total(), 5);
        assert!(result.has_skipped());
        assert!(!result.all_updated());
    }

    #[test]
    fn test_batch_update_result_all_updated() {
        let result: BatchUpdateResult<i32> = BatchUpdateResult::new(vec![1, 2], 0);
        assert!(!result.has_skipped());
        assert!(result.all_updated());
        assert_eq!(result.total(), 2);
    }

    #[test]
    fn test_batch_update_result_default() {
        let result: BatchUpdateResult<i32> = BatchUpdateResult::default();
        assert_eq!(result.updated_count(), 0);
        assert_eq!(result.skipped, 0);
        assert_eq!(result.total(), 0);
    }

    #[test]
    fn test_batch_update_result_map() {
        let result = BatchUpdateResult::new(vec![1, 2, 3], 1);
        let mapped = result.map(|x| x * 10);
        assert_eq!(mapped.updated, vec![10, 20, 30]);
        assert_eq!(mapped.skipped, 1);
    }

    #[test]
    fn test_repo_batch_update_all_existing() {
        // 所有实体都存在:全部更新,无跳过
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice", 30, "a@b.com"),
            User::new(2, "Bob", 25, "b@b.com"),
        ]);
        let updates = vec![
            User::new(1, "Alice Updated", 31, "a2@b.com"),
            User::new(2, "Bob Updated", 26, "b2@b.com"),
        ];
        let result = repo.batch_update(updates).unwrap();
        assert_eq!(result.updated_count(), 2);
        assert_eq!(result.skipped, 0);
        assert!(result.all_updated());

        // 验证实际更新生效
        let alice = repo.find_by_id(&Value::I64(1)).unwrap().unwrap();
        assert_eq!(alice.name, "Alice Updated");
        assert_eq!(alice.age, 31);
        let bob = repo.find_by_id(&Value::I64(2)).unwrap().unwrap();
        assert_eq!(bob.name, "Bob Updated");
        assert_eq!(bob.age, 26);
        // 总数不变(不是插入)
        assert_eq!(repo.len(), 2);
    }

    #[test]
    fn test_repo_batch_update_partial_missing() {
        // 部分实体不存在:仅更新存在的,跳过不存在的
        let repo = InMemoryRepository::from_vec(vec![User::new(1, "Alice", 30, "a@b.com")]);
        let updates = vec![
            User::new(1, "Alice Updated", 31, "a2@b.com"),
            User::new(999, "Ghost", 1, "ghost@b.com"), // 不存在
        ];
        let result = repo.batch_update(updates).unwrap();
        assert_eq!(result.updated_count(), 1);
        assert_eq!(result.skipped, 1);
        assert!(result.has_skipped());

        // 验证存在的实体被更新
        let alice = repo.find_by_id(&Value::I64(1)).unwrap().unwrap();
        assert_eq!(alice.name, "Alice Updated");
        // 不存在的实体不会被插入
        assert!(repo.find_by_id(&Value::I64(999)).unwrap().is_none());
        assert_eq!(repo.len(), 1);
    }

    #[test]
    fn test_repo_batch_update_all_missing() {
        // 所有实体都不存在:全部跳过
        let repo = InMemoryRepository::from_vec(vec![User::new(1, "Alice", 30, "a@b.com")]);
        let updates = vec![
            User::new(100, "Ghost1", 1, "g1@b.com"),
            User::new(200, "Ghost2", 2, "g2@b.com"),
        ];
        let result = repo.batch_update(updates).unwrap();
        assert_eq!(result.updated_count(), 0);
        assert_eq!(result.skipped, 2);
        assert_eq!(repo.len(), 1); // 原数据不变
    }

    #[test]
    fn test_repo_batch_update_empty() {
        let repo = InMemoryRepository::from_vec(vec![User::new(1, "Alice", 30, "a@b.com")]);
        let result = repo.batch_update(vec![]).unwrap();
        assert_eq!(result.updated_count(), 0);
        assert_eq!(result.skipped, 0);
        assert_eq!(result.total(), 0);
    }

    #[test]
    fn test_repo_batch_update_distinct_from_save_many() {
        // 验证 batch_update 与 save_many 语义不同:
        // - save_many 是 upsert(不存在的会插入)
        // - batch_update 是纯更新(不存在的会跳过)
        let repo1 = InMemoryRepository::from_vec(vec![User::new(1, "Alice", 30, "a@b.com")]);
        let repo2 = InMemoryRepository::from_vec(vec![User::new(1, "Alice", 30, "a@b.com")]);

        let updates = vec![
            User::new(1, "Alice Updated", 31, "a2@b.com"),
            User::new(999, "New User", 1, "new@b.com"),
        ];

        // save_many:两条都保存(id=999 会插入)
        let saved = repo1.save_many(updates.clone()).unwrap();
        assert_eq!(saved.len(), 2);
        assert_eq!(repo1.len(), 2); // 1 条原始 + 1 条新增

        // batch_update:仅 id=1 更新,id=999 跳过
        let result = repo2.batch_update(updates).unwrap();
        assert_eq!(result.updated_count(), 1);
        assert_eq!(result.skipped, 1);
        assert_eq!(repo2.len(), 1); // 不增加
    }

    #[test]
    fn test_repo_save_update_existing() {
        let repo = InMemoryRepository::<User>::new();
        repo.save(User::new(1, "Alice", 30, "alice@example.com"))
            .unwrap();

        // 更新
        repo.save(User::new(1, "Alice Updated", 31, "alice2@example.com"))
            .unwrap();

        assert_eq!(repo.len(), 1);
        let found = repo.find_by_id(&Value::I64(1)).unwrap().unwrap();
        assert_eq!(found.name, "Alice Updated");
        assert_eq!(found.age, 31);
    }

    #[test]
    fn test_repo_find_all() {
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice", 30, "a@b.com"),
            User::new(2, "Bob", 25, "b@b.com"),
        ]);
        let all = repo.find_all().unwrap();
        assert_eq!(all.len(), 2);
    }

    #[test]
    fn test_repo_find_all_empty() {
        let repo = InMemoryRepository::<User>::new();
        let all = repo.find_all().unwrap();
        assert!(all.is_empty());
    }

    #[test]
    fn test_repo_delete() {
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice", 30, "a@b.com"),
            User::new(2, "Bob", 25, "b@b.com"),
        ]);
        let deleted = repo.delete(&Value::I64(1)).unwrap();
        assert_eq!(deleted, 1);
        assert_eq!(repo.len(), 1);
    }

    #[test]
    fn test_repo_delete_missing() {
        let repo = InMemoryRepository::from_vec(vec![User::new(1, "Alice", 30, "a@b.com")]);
        let deleted = repo.delete(&Value::I64(999)).unwrap();
        assert_eq!(deleted, 0);
        assert_eq!(repo.len(), 1);
    }

    #[test]
    fn test_repo_count() {
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice", 30, "a@b.com"),
            User::new(2, "Bob", 25, "b@b.com"),
            User::new(3, "Carol", 28, "c@b.com"),
        ]);
        assert_eq!(repo.count().unwrap(), 3);
    }

    #[test]
    fn test_repo_count_empty() {
        let repo = InMemoryRepository::<User>::new();
        assert_eq!(repo.count().unwrap(), 0);
    }

    #[test]
    fn test_repo_exists() {
        let repo = InMemoryRepository::from_vec(vec![User::new(1, "Alice", 30, "a@b.com")]);
        assert!(repo.exists(&Value::I64(1)).unwrap());
        assert!(!repo.exists(&Value::I64(999)).unwrap());
    }

    // ===== Repository 条件查询 =====

    #[test]
    fn test_repo_find_by_eq() {
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice", 30, "a@b.com"),
            User::new(2, "Bob", 30, "b@b.com"),
            User::new(3, "Carol", 25, "c@b.com"),
        ]);

        let result = repo
            .find_by(&[WhereCondition::new("age", WhereOp::Eq, Value::I64(30))])
            .unwrap();
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_repo_find_by_gt() {
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice", 30, "a@b.com"),
            User::new(2, "Bob", 25, "b@b.com"),
            User::new(3, "Carol", 35, "c@b.com"),
        ]);

        let result = repo
            .find_by(&[WhereCondition::new("age", WhereOp::Gt, Value::I64(28))])
            .unwrap();
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_repo_find_by_like() {
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice", 30, "alice@example.com"),
            User::new(2, "Bob", 25, "bob@example.com"),
            User::new(3, "Alicia", 28, "alicia@test.com"),
        ]);

        let result = repo
            .find_by(&[WhereCondition::new(
                "name",
                WhereOp::Like,
                Value::String("Ali%".to_string()),
            )])
            .unwrap();
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_repo_find_by_like_case_insensitive() {
        // 对齐 MySQL utf8mb4_general_ci / utf8mb4_unicode_ci 默认 collation(大小写不敏感)
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice", 30, "alice@example.com"),
            User::new(2, "bob", 25, "bob@example.com"),
            User::new(3, "ALICIA", 28, "alicia@test.com"),
        ]);

        // 小写 pattern 应匹配大小写混合的数据
        let result = repo
            .find_by(&[WhereCondition::new(
                "name",
                WhereOp::Like,
                Value::String("ali%".to_string()),
            )])
            .unwrap();
        assert_eq!(result.len(), 2, "LIKE should be case-insensitive");

        // 大写 pattern 也应匹配小写数据
        let result = repo
            .find_by(&[WhereCondition::new(
                "name",
                WhereOp::Like,
                Value::String("BOB".to_string()),
            )])
            .unwrap();
        assert_eq!(
            result.len(),
            1,
            "LIKE exact match should be case-insensitive"
        );
    }

    #[test]
    fn test_repo_find_by_with_or_filter_multi_field_keyword() {
        // 对齐 PHP ThinkPHP `where('field1|field2|field3','like','%kw%')` 多字段 OR LIKE
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice", 30, "alice@example.com"),
            User::new(2, "Bob", 25, "bob@example.com"),
            User::new(3, "Carol", 28, "carol@kw.com"), // email 含 kw
            User::new(4, "Dave", 32, "dave@example.com"),
        ]);

        let and = vec![]; // 无 AND 条件
        let or = vec![
            WhereCondition::new("name", WhereOp::Like, Value::String("%kw%".to_string())),
            WhereCondition::new("email", WhereOp::Like, Value::String("%kw%".to_string())),
        ];

        let result = repo.find_by_with_or_filter(&and, &or).unwrap();
        // 只有 Carol 的 email 含 kw
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].key(), 3);
    }

    #[test]
    fn test_repo_find_by_with_or_filter_combined_with_and() {
        // AND + OR 组合:对齐 PHP `where(is_delete=0 AND app_id=1) AND (name LIKE %kw% OR addr LIKE %kw%)`
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice_kw", 30, "alice@example.com"), // app_id=1, name 含 kw
            User::new(2, "Bob", 25, "bob@kw.com"),             // app_id=1, email 含 kw
            User::new(3, "Carol_kw", 28, "carol@example.com"), // app_id=2, name 含 kw(被 AND 排除)
            User::new(4, "Dave", 32, "dave@example.com"),      // app_id=1, 无 kw
        ]);

        // User struct 没有 app_id 字段,用 age 模拟 AND 条件:age >= 28
        let and = vec![WhereCondition::new("age", WhereOp::Ge, Value::I64(28))];
        let or = vec![
            WhereCondition::new("name", WhereOp::Like, Value::String("%kw%".to_string())),
            WhereCondition::new("email", WhereOp::Like, Value::String("%kw%".to_string())),
        ];

        let result = repo.find_by_with_or_filter(&and, &or).unwrap();
        // age >= 28: Alice(30), Carol(28), Dave(32)
        // 其中 name 或 email 含 kw: Alice(name), Carol(name), Bob(email 不满足 age>=28)
        // 但 Carol age=28 满足 >= 28,所以 Carol 也应被选中
        assert_eq!(result.len(), 2);
        let ids: Vec<i64> = result.iter().map(|u| u.key()).collect();
        assert!(ids.contains(&1));
        assert!(ids.contains(&3));
    }

    #[test]
    fn test_repo_find_by_with_or_filter_empty_or() {
        // or_filter 为空时应等同于 find_by
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice", 30, "alice@example.com"),
            User::new(2, "Bob", 25, "bob@example.com"),
        ]);

        let and = vec![WhereCondition::new("age", WhereOp::Ge, Value::I64(28))];
        let or: Vec<WhereCondition> = vec![];

        let result = repo.find_by_with_or_filter(&and, &or).unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].key(), 1);
    }

    #[test]
    fn test_repo_find_by_in() {
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice", 30, "a@b.com"),
            User::new(2, "Bob", 25, "b@b.com"),
            User::new(3, "Carol", 28, "c@b.com"),
            User::new(4, "Dave", 32, "d@b.com"),
        ]);

        let result = repo
            .find_by(&[WhereCondition::in_op(
                "id",
                WhereOp::In,
                vec![Value::I64(1), Value::I64(3)],
            )])
            .unwrap();
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_repo_find_by_not_in() {
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice", 30, "a@b.com"),
            User::new(2, "Bob", 25, "b@b.com"),
            User::new(3, "Carol", 28, "c@b.com"),
        ]);

        let result = repo
            .find_by(&[WhereCondition::in_op(
                "id",
                WhereOp::NotIn,
                vec![Value::I64(1)],
            )])
            .unwrap();
        assert_eq!(result.len(), 2);
        assert!(result.iter().all(|u| u.id != 1));
    }

    #[test]
    fn test_repo_find_by_between() {
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice", 30, "a@b.com"),
            User::new(2, "Bob", 25, "b@b.com"),
            User::new(3, "Carol", 35, "c@b.com"),
            User::new(4, "Dave", 22, "d@b.com"),
        ]);

        let result = repo
            .find_by(&[WhereCondition::between(
                "age",
                Value::I64(25),
                Value::I64(35),
            )])
            .unwrap();
        assert_eq!(result.len(), 3);
    }

    #[test]
    fn test_repo_find_by_multiple_conditions() {
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice", 30, "a@b.com"),
            User::new(2, "Bob", 30, "b@b.com"),
            User::new(3, "Alice", 25, "c@b.com"),
        ]);

        let result = repo
            .find_by(&[
                WhereCondition::new("name", WhereOp::Eq, Value::String("Alice".to_string())),
                WhereCondition::new("age", WhereOp::Ge, Value::I64(30)),
            ])
            .unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].id, 1);
    }

    #[test]
    fn test_repo_find_one_by() {
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice", 30, "a@b.com"),
            User::new(2, "Bob", 25, "b@b.com"),
        ]);

        let result = repo
            .find_one_by(&[WhereCondition::new(
                "name",
                WhereOp::Eq,
                Value::String("Bob".to_string()),
            )])
            .unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().id, 2);
    }

    #[test]
    fn test_repo_find_one_by_missing() {
        let repo = InMemoryRepository::from_vec(vec![User::new(1, "Alice", 30, "a@b.com")]);

        let result = repo
            .find_one_by(&[WhereCondition::new(
                "name",
                WhereOp::Eq,
                Value::String("Missing".to_string()),
            )])
            .unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_repo_count_by() {
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice", 30, "a@b.com"),
            User::new(2, "Bob", 30, "b@b.com"),
            User::new(3, "Carol", 25, "c@b.com"),
        ]);

        let count = repo
            .count_by(&[WhereCondition::new("age", WhereOp::Eq, Value::I64(30))])
            .unwrap();
        assert_eq!(count, 2);
    }

    #[test]
    fn test_repo_delete_by() {
        let repo = InMemoryRepository::from_vec(vec![
            User::new(1, "Alice", 30, "a@b.com"),
            User::new(2, "Bob", 30, "b@b.com"),
            User::new(3, "Carol", 25, "c@b.com"),
        ]);

        let deleted = repo
            .delete_by(&[WhereCondition::new("age", WhereOp::Eq, Value::I64(30))])
            .unwrap();
        assert_eq!(deleted, 2);
        assert_eq!(repo.len(), 1);
    }

    // ===== 分页 =====

    #[test]
    fn test_repo_paginate() {
        let users: Vec<User> = (1..=25)
            .map(|i| User::new(i, &format!("User{}", i), 20 + (i % 30), "u@b.com"))
            .collect();
        let repo = InMemoryRepository::from_vec(users);

        let page = repo.paginate(1, 10).unwrap();
        assert_eq!(page.page, 1);
        assert_eq!(page.page_size, 10);
        assert_eq!(page.total, 25);
        assert_eq!(page.total_pages(), 3);
        assert_eq!(page.items.len(), 10);
        assert!(page.has_next());
        assert!(!page.has_prev());
    }

    #[test]
    fn test_repo_paginate_last_page() {
        let users: Vec<User> = (1..=25)
            .map(|i| User::new(i, &format!("User{}", i), 20, "u@b.com"))
            .collect();
        let repo = InMemoryRepository::from_vec(users);

        let page = repo.paginate(3, 10).unwrap();
        assert_eq!(page.items.len(), 5);
        assert!(page.has_prev());
        assert!(!page.has_next());
    }

    #[test]
    fn test_repo_paginate_out_of_range() {
        let users: Vec<User> = (1..=5)
            .map(|i| User::new(i, &format!("User{}", i), 20, "u@b.com"))
            .collect();
        let repo = InMemoryRepository::from_vec(users);

        let page = repo.paginate(10, 10).unwrap();
        assert_eq!(page.items.len(), 0);
        assert_eq!(page.total, 5);
    }

    #[test]
    fn test_repo_paginate_by() {
        let users: Vec<User> = (1..=20)
            .map(|i| User::new(i, &format!("User{}", i), 20 + (i % 5), "u@b.com"))
            .collect();
        let repo = InMemoryRepository::from_vec(users);

        // age=22 的用户:i=2,7,12,17 → 4 个
        let page = repo
            .paginate_by(
                &[WhereCondition::new("age", WhereOp::Eq, Value::I64(22))],
                1,
                2,
            )
            .unwrap();
        assert_eq!(page.total, 4);
        assert_eq!(page.items.len(), 2);
        assert_eq!(page.total_pages(), 2);
    }

    // ===== GenericKeyRepository =====

    #[test]
    fn test_generic_key_repo_basic() {
        let repo: GenericKeyRepository<User, i64> = GenericKeyRepository::new();
        assert!(repo.is_empty());

        let user = User::new(1, "Alice", 30, "a@b.com");
        repo.save(user.clone()).unwrap();
        assert_eq!(repo.len(), 1);

        let found = repo.find_by_id(&1).unwrap();
        assert_eq!(found, Some(user));
    }

    #[test]
    fn test_generic_key_repo_delete() {
        let repo: GenericKeyRepository<User, i64> = GenericKeyRepository::from_vec(vec![
            User::new(1, "Alice", 30, "a@b.com"),
            User::new(2, "Bob", 25, "b@b.com"),
        ]);

        let deleted = repo.delete(&1).unwrap();
        assert_eq!(deleted, 1);
        assert_eq!(repo.len(), 1);

        let remaining = repo.find_all().unwrap();
        assert_eq!(remaining[0].id, 2);
    }

    #[test]
    fn test_generic_key_repo_find_by() {
        let repo: GenericKeyRepository<User, i64> = GenericKeyRepository::from_vec(vec![
            User::new(1, "Alice", 30, "a@b.com"),
            User::new(2, "Bob", 30, "b@b.com"),
            User::new(3, "Carol", 25, "c@b.com"),
        ]);

        let result = repo
            .find_by(&[WhereCondition::new("age", WhereOp::Eq, Value::I64(30))])
            .unwrap();
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_generic_key_repo_paginate() {
        let users: Vec<User> = (1..=15)
            .map(|i| User::new(i, &format!("User{}", i), 20, "u@b.com"))
            .collect();
        let repo: GenericKeyRepository<User, i64> = GenericKeyRepository::from_vec(users);

        let page = repo.paginate(2, 10).unwrap();
        assert_eq!(page.items.len(), 5);
        assert_eq!(page.total, 15);
        assert_eq!(page.page, 2);
    }

    #[test]
    fn test_generic_key_repo_count() {
        let repo: GenericKeyRepository<User, i64> = GenericKeyRepository::from_vec(vec![
            User::new(1, "Alice", 30, "a@b.com"),
            User::new(2, "Bob", 25, "b@b.com"),
        ]);
        assert_eq!(repo.count().unwrap(), 2);
    }

    #[test]
    fn test_generic_key_repo_exists() {
        let repo: GenericKeyRepository<User, i64> =
            GenericKeyRepository::from_vec(vec![User::new(1, "Alice", 30, "a@b.com")]);
        assert!(repo.exists(&1).unwrap());
        assert!(!repo.exists(&999).unwrap());
    }

    // ===== simple_regex =====

    #[test]
    fn test_simple_regex_literal() {
        let re = simple_regex::compile("^abc$").unwrap();
        assert!(re.is_match("abc"));
        assert!(!re.is_match("abcd"));
    }

    #[test]
    fn test_simple_regex_wildcard() {
        let re = simple_regex::compile("^Ali.*$").unwrap();
        assert!(re.is_match("Alice"));
        assert!(re.is_match("Alicia"));
        assert!(!re.is_match("Bob"));
    }

    #[test]
    fn test_simple_regex_no_anchors() {
        let re = simple_regex::compile("ab").unwrap();
        assert!(re.is_match("ab"));
    }

    // ===== 端到端场景 =====

    #[test]
    fn test_e2e_repository_workflow() {
        let repo = InMemoryRepository::<User>::new();

        // 1. 批量插入
        let users = vec![
            User::new(1, "Alice", 30, "alice@example.com"),
            User::new(2, "Bob", 25, "bob@example.com"),
            User::new(3, "Carol", 35, "carol@example.com"),
            User::new(4, "Dave", 28, "dave@example.com"),
            User::new(5, "Eve", 32, "eve@example.com"),
        ];
        repo.save_many(users).unwrap();
        assert_eq!(repo.count().unwrap(), 5);

        // 2. 查找成年人(age >= 30)
        let adults = repo
            .find_by(&[WhereCondition::new("age", WhereOp::Ge, Value::I64(30))])
            .unwrap();
        assert_eq!(adults.len(), 3);

        // 3. 分页查询
        let page1 = repo.paginate(1, 2).unwrap();
        assert_eq!(page1.items.len(), 2);
        assert_eq!(page1.total_pages(), 3);

        let page2 = repo.paginate(2, 2).unwrap();
        assert_eq!(page2.items.len(), 2);

        let page3 = repo.paginate(3, 2).unwrap();
        assert_eq!(page3.items.len(), 1);

        // 4. 条件分页查询(age >= 30)
        let adult_page = repo
            .paginate_by(
                &[WhereCondition::new("age", WhereOp::Ge, Value::I64(30))],
                1,
                2,
            )
            .unwrap();
        assert_eq!(adult_page.total, 3);
        assert_eq!(adult_page.items.len(), 2);

        // 5. 更新
        repo.save(User::new(1, "Alice Smith", 31, "alice.smith@example.com"))
            .unwrap();
        let updated = repo.find_by_id(&Value::I64(1)).unwrap().unwrap();
        assert_eq!(updated.name, "Alice Smith");
        assert_eq!(updated.age, 31);

        // 6. 删除
        let deleted = repo.delete(&Value::I64(2)).unwrap();
        assert_eq!(deleted, 1);
        assert_eq!(repo.count().unwrap(), 4);
        assert!(!repo.exists(&Value::I64(2)).unwrap());

        // 7. 条件删除 age >= 31:Alice(31) + Carol(35) + Eve(32) = 3 个
        let deleted_by = repo
            .delete_by(&[WhereCondition::new("age", WhereOp::Ge, Value::I64(31))])
            .unwrap();
        assert_eq!(deleted_by, 3);
        assert_eq!(repo.count().unwrap(), 1); // 仅剩 Dave(28)
    }

    #[test]
    fn test_e2e_pagination_navigation() {
        let users: Vec<User> = (1..=100)
            .map(|i| User::new(i, &format!("User{}", i), 20, "u@b.com"))
            .collect();
        let repo = InMemoryRepository::from_vec(users);

        let mut current_page = 1u64;
        let mut visited: Vec<u64> = Vec::new();
        loop {
            let page = repo.paginate(current_page, 10).unwrap();
            visited.push(current_page);
            if !page.has_next() {
                break;
            }
            current_page += 1;
        }
        assert_eq!(visited.len(), 10);
        assert_eq!(visited, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
    }

    // ===== 安全限制:TooManyRows =====

    #[test]
    fn test_paginate_too_many_rows() {
        // 直接构造 TooManyRows 错误,验证变体和 Display 信息
        let err = RepositoryError::TooManyRows {
            actual: 200_000,
            limit: REPOSITORY_SCAN_LIMIT,
        };
        assert!(matches!(err, RepositoryError::TooManyRows { actual: 200_000, limit } if limit == REPOSITORY_SCAN_LIMIT));
        let msg = err.to_string();
        assert!(msg.contains("200000"), "msg should contain actual count: {}", msg);
        assert!(msg.contains("100000"), "msg should contain limit: {}", msg);
    }

    #[test]
    fn test_paginate_boundary_at_limit() {
        // 行数恰好等于 REPOSITORY_SCAN_LIMIT:允许通过(不触发限制)
        // 用较小数据集验证 count 路径正确:count == total 且 paginate 正常返回
        let n: usize = 50;
        let users: Vec<User> = (1..=n as i64)
            .map(|i| User::new(i, &format!("U{}", i), 20, "u@b.com"))
            .collect();
        let repo = InMemoryRepository::from_vec(users);
        // 远低于上限,paginate 应正常返回
        assert_eq!(repo.count().unwrap() as usize, n);
        let page = repo.paginate(1, 10).unwrap();
        assert_eq!(page.total, n as u64);
        assert_eq!(page.items.len(), 10);
        // 验证错误变体的 Display 信息包含关键数值
        let err = RepositoryError::TooManyRows {
            actual: REPOSITORY_SCAN_LIMIT + 1,
            limit: REPOSITORY_SCAN_LIMIT,
        };
        let msg = err.to_string();
        assert!(msg.contains("QueryBuilder"), "msg should suggest QueryBuilder: {}", msg);
    }
}