garrison 0.9.0

Garrison - 面向 Rust 生态的一站式身份认证鉴权框架
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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! Repository 层模块:为 9 张核心表定义 Repository trait(CRUD 抽象),SQLite 实现见 `sqlite` 子模块(`db-sqlite`)。
//!
//! ## 设计要点
//!
//! - `tenant_id` 统一 `i64`(INTEGER 索引紧凑、类型安全、与 `TenantContext.tenant_id` 一致);需业务码(`tenant_001`)时由调用方维护映射,DAO 只认 i64。
//! - `create` 返回 `String`(UUID)而非 `LoginId`:dao 模块不依赖 stp 模块(分层原则)。
//!
//! ## 9 张核心表
//!
//! | 表名 | trait | tenant_id | 说明 |
//! |:---|:---|:---:|:---|
//! | app_user | [`UserRepository`] | 是 | 用户主表 |
//! | app_role | [`RoleRepository`] | 是 | 角色表 |
//! | app_permission | [`PermissionRepository`] | 否 | 权限表(全局共享) |
//! | app_user_role | [`UserRoleRepository`] | 是 | 用户-角色关联 |
//! | app_role_permission | [`RolePermissionRepository`] | 是 | 角色-权限关联 |
//! | app_auth_method | [`AuthMethodRepository`] | 是 | 认证方式表 |
//! | app_session | [`SessionRepository`] | 是 | 会话表 |
//! | app_login_log | [`LoginLogRepository`] | 是 | 登录日志表 |
//! | app_user_ext | [`UserExtRepository`] | 是 | 用户扩展字段表 |
//! | app_user_device | [`UserDeviceRepository`] | 是 | 用户设备表 |

use crate::error::GarrisonResult;

// Row struct 定义

/// 用户表行(app_user)。
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UserRow {
    /// 用户 ID(UUID 字符串)。
    pub id: String,
    /// 用户名。
    pub username: String,
    /// 密码哈希(argon2/bcrypt)。
    pub password_hash: String,
    /// 状态(pending/active/suspended/inactive/deleted)。
    pub status: String,
    /// 租户 ID。
    pub tenant_id: i64,
    /// 创建时间(ISO 8601 字符串)。
    pub created_at: String,
    /// 更新时间。
    pub updated_at: String,
    /// 最后登录时间(可空)。
    pub last_login_at: Option<String>,
}

/// 用户列表行(app_user,不含 password_hash 的投影)。
///
/// [`UserRepository::list`] 专用:从类型上排除 `password_hash`,杜绝凭证经分页/浏览接口
/// 序列化到 API 响应或日志(编译期防护);需要哈希的认证查询用 `find_by_id` / `find_by_username`。
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UserListRow {
    /// 用户 ID(UUID 字符串)。
    pub id: String,
    /// 用户名。
    pub username: String,
    /// 状态(pending/active/suspended/inactive/deleted)。
    pub status: String,
    /// 租户 ID。
    pub tenant_id: i64,
    /// 创建时间(ISO 8601 字符串)。
    pub created_at: String,
    /// 更新时间。
    pub updated_at: String,
    /// 最后登录时间(可空)。
    pub last_login_at: Option<String>,
}

/// 新建用户参数。
#[derive(Debug, Clone)]
pub struct NewUser {
    /// 用户名。
    pub username: String,
    /// 密码哈希。
    pub password_hash: String,
    /// 状态。
    pub status: String,
}

/// 更新用户参数(所有字段可选,None 表示不更新)。
#[derive(Debug, Clone, Default)]
pub struct UpdateUser {
    /// 用户名。
    pub username: Option<String>,
    /// 密码哈希。
    pub password_hash: Option<String>,
    /// 状态。
    pub status: Option<String>,
    /// 最后登录时间。
    pub last_login_at: Option<String>,
}

// 导入哈希参数防御上限(防单次登录 OOM / CPU DoS);实现见 `hash_import`,此处仅声明与 re-export。

mod hash_import;
pub use hash_import::{
    validate_imported_hash, ARGON2_IMPORT_MAX_M_COST, ARGON2_IMPORT_MAX_P, ARGON2_IMPORT_MAX_T,
    BCRYPT_IMPORT_MAX_COST,
};

/// 角色表行(app_role)。
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoleRow {
    /// 角色 ID(UUID)。
    pub id: String,
    /// 角色编码(业务用)。
    pub code: String,
    /// 角色名(展示用)。
    pub name: String,
    /// 描述。
    pub description: Option<String>,
    /// 租户 ID。
    pub tenant_id: i64,
    /// 是否系统内置角色。
    pub is_system: bool,
    /// 创建时间。
    pub created_at: String,
    /// 更新时间。
    pub updated_at: String,
}

/// 新建角色参数。
#[derive(Debug, Clone)]
pub struct NewRole {
    /// 角色编码。
    pub code: String,
    /// 角色名。
    pub name: String,
    /// 描述。
    pub description: Option<String>,
    /// 是否系统内置。
    pub is_system: bool,
}

/// 权限表行(app_permission,全局表无 tenant_id)。
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PermissionRow {
    /// 权限 ID(UUID)。
    pub id: String,
    /// 权限编码(全局唯一)。
    pub code: String,
    /// 权限名。
    pub name: String,
    /// 资源类型(如 user/role/order)。
    pub resource_type: Option<String>,
    /// 动作(如 read/write/delete)。
    pub action: Option<String>,
    /// 创建时间。
    pub created_at: String,
    /// 更新时间。
    pub updated_at: String,
}

/// 新建权限参数。
#[derive(Debug, Clone)]
pub struct NewPermission {
    /// 权限编码。
    pub code: String,
    /// 权限名。
    pub name: String,
    /// 资源类型。
    pub resource_type: Option<String>,
    /// 动作。
    pub action: Option<String>,
}

/// 用户-角色关联表行(app_user_role)。
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UserRoleRow {
    /// 用户 ID。
    pub user_id: String,
    /// 角色 ID。
    pub role_id: String,
    /// 授权范围。
    pub scope: Option<String>,
    /// 授权时间。
    pub grant_time: String,
    /// 租户 ID。
    pub tenant_id: i64,
}

/// 角色-权限关联表行(app_role_permission)。
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RolePermissionRow {
    /// 角色 ID。
    pub role_id: String,
    /// 权限 ID。
    pub permission_id: String,
    /// 租户 ID。
    pub tenant_id: i64,
}

/// 认证方式表行(app_auth_method)。
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AuthMethodRow {
    /// 认证方式 ID(UUID)。
    pub id: String,
    /// 用户 ID。
    pub user_id: String,
    /// 认证类型(passkey/password/oauth/did)。
    pub method_type: String,
    /// 外部 ID(如 OAuth provider user id)。
    pub external_id: Option<String>,
    /// JSON 元数据。
    pub metadata: Option<String>,
    /// 创建时间。
    pub create_time: String,
    /// 租户 ID。
    pub tenant_id: i64,
}

/// 新建认证方式参数。
#[derive(Debug, Clone)]
pub struct NewAuthMethod {
    /// 用户 ID。
    pub user_id: String,
    /// 认证类型。
    pub method_type: String,
    /// 外部 ID。
    pub external_id: Option<String>,
    /// JSON 元数据。
    pub metadata: Option<String>,
}

/// 会话表行(app_session)。
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SessionRow {
    /// 会话 ID(Token)。
    pub session_id: String,
    /// 用户 ID。
    pub user_id: String,
    /// 设备 ID。
    pub device_id: Option<String>,
    /// 登录 IP。
    pub ip: Option<String>,
    /// User-Agent。
    pub user_agent: Option<String>,
    /// 登录时间。
    pub login_time: String,
    /// 最后活跃时间。
    pub last_active: String,
    /// 过期时间。
    pub expire_time: Option<String>,
    /// 租户 ID。
    pub tenant_id: i64,
}

/// 新建会话参数。
#[derive(Debug, Clone)]
pub struct NewSession {
    /// 会话 ID(Token)。
    pub session_id: String,
    /// 用户 ID。
    pub user_id: String,
    /// 设备 ID。
    pub device_id: Option<String>,
    /// 登录 IP。
    pub ip: Option<String>,
    /// User-Agent。
    pub user_agent: Option<String>,
    /// 过期时间。
    pub expire_time: Option<String>,
}

/// 登录日志表行(app_login_log)。
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct LoginLogRow {
    /// 日志 ID(UUID)。
    pub id: String,
    /// 用户 ID(可空,登录失败时可能无 user)。
    pub user_id: Option<String>,
    /// 动作(login/logout/refresh/kickout/kicked)。
    pub action: String,
    /// IP。
    pub ip: Option<String>,
    /// 设备 ID。
    pub device_id: Option<String>,
    /// 是否成功。
    pub success: bool,
    /// 失败原因。
    pub fail_reason: Option<String>,
    /// 创建时间。
    pub create_time: String,
    /// 租户 ID。
    pub tenant_id: i64,
}

/// 新建登录日志参数。
#[derive(Debug, Clone)]
pub struct NewLoginLog {
    /// 用户 ID。
    pub user_id: Option<String>,
    /// 动作。
    pub action: String,
    /// IP。
    pub ip: Option<String>,
    /// 设备 ID。
    pub device_id: Option<String>,
    /// 是否成功。
    pub success: bool,
    /// 失败原因。
    pub fail_reason: Option<String>,
}

/// 用户扩展字段表行(app_user_ext)。
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UserExtRow {
    /// 扩展字段 ID(UUID)。
    pub id: String,
    /// 用户 ID。
    pub user_id: String,
    /// 扩展字段键(如 email/phone/avatar)。
    pub field_key: String,
    /// 扩展字段值。
    pub field_value: Option<String>,
    /// 字段类型(string/number/boolean/json/datetime)。
    pub field_type: String,
    /// 创建时间。
    pub created_at: String,
    /// 更新时间。
    pub updated_at: String,
    /// 租户 ID。
    pub tenant_id: i64,
}

/// 用户设备表行(app_user_device):设备指纹与 UA 信息,供设备阻断与多设备管理;时间字段为 epoch seconds。
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UserDeviceRow {
    /// 设备 ID(UUID v4)。
    pub id: String,
    /// 租户 ID。
    pub tenant_id: i64,
    /// 登录 ID(字符串形式,关联 app_login_log 或外部 login 概念)。
    pub login_id: String,
    /// 设备标识(UA hash 或设备指纹)。
    pub device_identifier: String,
    /// 设备名(从 UA 解析,如 "Chrome on Windows")。
    pub device_name: Option<String>,
    /// 原始 User-Agent 字符串。
    pub user_agent: Option<String>,
    /// 是否被阻止。
    pub is_blocked: bool,
    /// 最后活跃时间(epoch seconds,可空)。
    pub last_seen_at: Option<i64>,
    /// 创建时间(epoch seconds)。
    pub created_at: i64,
}

// Repository trait 定义

/// 用户表 Repository trait。
///
/// 所有方法首参 `tenant_id` 用于多租户过滤。
#[async_trait::async_trait]
pub trait UserRepository: Send + Sync {
    /// 按 ID 查询用户。
    async fn find_by_id(&self, tenant_id: i64, id: &str) -> GarrisonResult<Option<UserRow>>;

    /// 按 username 查询用户。
    async fn find_by_username(
        &self,
        tenant_id: i64,
        username: &str,
    ) -> GarrisonResult<Option<UserRow>>;

    /// 创建用户,返回新插入的 ID。
    async fn create(&self, tenant_id: i64, user: NewUser) -> GarrisonResult<String>;

    /// 更新用户。
    async fn update(&self, tenant_id: i64, id: &str, user: UpdateUser) -> GarrisonResult<()>;

    /// 删除用户(幂等,不存在返回 Ok(()))。
    async fn delete(&self, tenant_id: i64, id: &str) -> GarrisonResult<()>;

    /// 分页查询用户(按 `id` 稳定排序,保证 LIMIT/OFFSET 分页确定性)。
    ///
    /// 返回 [`UserListRow`](不含 `password_hash` 的投影):分页/浏览场景
    /// 无需凭证数据,从类型上排除密码哈希泄漏。需要哈希的认证查询请使用
    /// `find_by_id` / `find_by_username`。
    async fn list(
        &self,
        tenant_id: i64,
        offset: i64,
        limit: i64,
    ) -> GarrisonResult<Vec<UserListRow>>;
}

/// 角色表 Repository trait。
#[async_trait::async_trait]
pub trait RoleRepository: Send + Sync {
    /// 按 ID 查询角色。
    async fn find_by_id(&self, tenant_id: i64, id: &str) -> GarrisonResult<Option<RoleRow>>;

    /// 按 code 查询角色。
    async fn find_by_code(&self, tenant_id: i64, code: &str) -> GarrisonResult<Option<RoleRow>>;

    /// 创建角色。
    async fn create(&self, tenant_id: i64, role: NewRole) -> GarrisonResult<String>;

    /// 更新角色。
    async fn update(
        &self,
        tenant_id: i64,
        id: &str,
        code: Option<String>,
        name: Option<String>,
        description: Option<String>,
    ) -> GarrisonResult<()>;

    /// 删除角色(幂等)。
    async fn delete(&self, tenant_id: i64, id: &str) -> GarrisonResult<()>;

    /// 分页查询角色。
    async fn list(&self, tenant_id: i64, offset: i64, limit: i64) -> GarrisonResult<Vec<RoleRow>>;
}

/// 权限表 Repository trait(全局表,无 tenant_id)。
#[async_trait::async_trait]
pub trait PermissionRepository: Send + Sync {
    /// 按 ID 查询权限。
    async fn find_by_id(&self, id: &str) -> GarrisonResult<Option<PermissionRow>>;

    /// 按 code 查询权限。
    async fn find_by_code(&self, code: &str) -> GarrisonResult<Option<PermissionRow>>;

    /// 创建权限。
    async fn create(&self, permission: NewPermission) -> GarrisonResult<String>;

    /// 更新权限。
    async fn update(
        &self,
        id: &str,
        name: Option<String>,
        resource_type: Option<String>,
        action: Option<String>,
    ) -> GarrisonResult<()>;

    /// 删除权限(幂等)。
    async fn delete(&self, id: &str) -> GarrisonResult<()>;

    /// 分页查询权限。
    async fn list(&self, offset: i64, limit: i64) -> GarrisonResult<Vec<PermissionRow>>;
}

/// 用户-角色关联 Repository trait。
#[async_trait::async_trait]
pub trait UserRoleRepository: Send + Sync {
    /// 查询用户的所有角色关联。
    async fn find_by_user_id(
        &self,
        tenant_id: i64,
        user_id: &str,
    ) -> GarrisonResult<Vec<UserRoleRow>>;

    /// 查询角色的所有用户关联。
    async fn find_by_role_id(
        &self,
        tenant_id: i64,
        role_id: &str,
    ) -> GarrisonResult<Vec<UserRoleRow>>;

    /// 分配角色给用户。
    async fn assign(
        &self,
        tenant_id: i64,
        user_id: &str,
        role_id: &str,
        scope: Option<String>,
    ) -> GarrisonResult<()>;

    /// 撤销用户的角色(幂等)。
    async fn revoke(&self, tenant_id: i64, user_id: &str, role_id: &str) -> GarrisonResult<()>;

    /// 分页查询。
    async fn list(
        &self,
        tenant_id: i64,
        offset: i64,
        limit: i64,
    ) -> GarrisonResult<Vec<UserRoleRow>>;
}

/// 角色-权限关联 Repository trait。
#[async_trait::async_trait]
pub trait RolePermissionRepository: Send + Sync {
    /// 查询角色的所有权限关联。
    async fn find_by_role_id(
        &self,
        tenant_id: i64,
        role_id: &str,
    ) -> GarrisonResult<Vec<RolePermissionRow>>;

    /// 查询权限的所有角色关联。
    async fn find_by_permission_id(
        &self,
        tenant_id: i64,
        permission_id: &str,
    ) -> GarrisonResult<Vec<RolePermissionRow>>;

    /// 分配权限给角色。
    async fn assign(
        &self,
        tenant_id: i64,
        role_id: &str,
        permission_id: &str,
    ) -> GarrisonResult<()>;

    /// 撤销角色的权限(幂等)。
    async fn revoke(
        &self,
        tenant_id: i64,
        role_id: &str,
        permission_id: &str,
    ) -> GarrisonResult<()>;

    /// 分页查询。
    async fn list(
        &self,
        tenant_id: i64,
        offset: i64,
        limit: i64,
    ) -> GarrisonResult<Vec<RolePermissionRow>>;
}

/// 认证方式 Repository trait。
#[async_trait::async_trait]
pub trait AuthMethodRepository: Send + Sync {
    /// 按 ID 查询认证方式。
    async fn find_by_id(&self, tenant_id: i64, id: &str) -> GarrisonResult<Option<AuthMethodRow>>;

    /// 查询用户的所有认证方式。
    async fn find_by_user_id(
        &self,
        tenant_id: i64,
        user_id: &str,
    ) -> GarrisonResult<Vec<AuthMethodRow>>;

    /// 创建认证方式。
    async fn create(&self, tenant_id: i64, method: NewAuthMethod) -> GarrisonResult<String>;

    /// 删除认证方式(幂等)。
    async fn delete(&self, tenant_id: i64, id: &str) -> GarrisonResult<()>;

    /// 分页查询。
    async fn list(
        &self,
        tenant_id: i64,
        offset: i64,
        limit: i64,
    ) -> GarrisonResult<Vec<AuthMethodRow>>;
}

/// 会话 Repository trait。
#[async_trait::async_trait]
pub trait SessionRepository: Send + Sync {
    /// 按 session_id 查询会话。
    async fn find_by_session_id(
        &self,
        tenant_id: i64,
        session_id: &str,
    ) -> GarrisonResult<Option<SessionRow>>;

    /// 查询用户的所有会话。
    async fn find_by_user_id(
        &self,
        tenant_id: i64,
        user_id: &str,
    ) -> GarrisonResult<Vec<SessionRow>>;

    /// 创建会话。
    async fn create(&self, tenant_id: i64, session: NewSession) -> GarrisonResult<String>;

    /// 更新最后活跃时间。
    async fn update_last_active(&self, tenant_id: i64, session_id: &str) -> GarrisonResult<()>;

    /// 删除会话(幂等)。
    async fn delete(&self, tenant_id: i64, session_id: &str) -> GarrisonResult<()>;

    /// 分页查询。
    async fn list(
        &self,
        tenant_id: i64,
        offset: i64,
        limit: i64,
    ) -> GarrisonResult<Vec<SessionRow>>;
}

/// 登录日志 Repository trait。
#[async_trait::async_trait]
pub trait LoginLogRepository: Send + Sync {
    /// 按 ID 查询日志。
    async fn find_by_id(&self, tenant_id: i64, id: &str) -> GarrisonResult<Option<LoginLogRow>>;

    /// 查询用户的登录日志(分页)。
    async fn find_by_user_id(
        &self,
        tenant_id: i64,
        user_id: &str,
        offset: i64,
        limit: i64,
    ) -> GarrisonResult<Vec<LoginLogRow>>;

    /// 创建日志。
    async fn create(&self, tenant_id: i64, log: NewLoginLog) -> GarrisonResult<String>;

    /// 分页查询。
    async fn list(
        &self,
        tenant_id: i64,
        offset: i64,
        limit: i64,
    ) -> GarrisonResult<Vec<LoginLogRow>>;
}

/// 用户扩展字段 Repository trait。
#[async_trait::async_trait]
pub trait UserExtRepository: Send + Sync {
    /// 查询用户的所有扩展字段。
    async fn find_by_user_id(
        &self,
        tenant_id: i64,
        user_id: &str,
    ) -> GarrisonResult<Vec<UserExtRow>>;

    /// 按 user_id + field_key 查询。
    async fn find_by_user_and_key(
        &self,
        tenant_id: i64,
        user_id: &str,
        field_key: &str,
    ) -> GarrisonResult<Option<UserExtRow>>;

    /// 插入或更新扩展字段。
    async fn upsert(
        &self,
        tenant_id: i64,
        user_id: &str,
        field_key: &str,
        field_value: Option<String>,
        field_type: &str,
    ) -> GarrisonResult<()>;

    /// 删除扩展字段(幂等)。
    async fn delete(&self, tenant_id: i64, user_id: &str, field_key: &str) -> GarrisonResult<()>;

    /// 分页查询。
    async fn list(
        &self,
        tenant_id: i64,
        offset: i64,
        limit: i64,
    ) -> GarrisonResult<Vec<UserExtRow>>;
}

// 登录标识唯一性(app_user_identifier)

/// 标识注册结果。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RegisterOutcome {
    /// 注册成功(该标识此前未被占用)。
    ///
    /// 全局主键 `(id_type, id_value)` 冲突但命中行属**其他租户**时同样返回本变体
    /// (中性「已注册」,不带 `by_user_id`)——不得从返回值推断该标识在当前租户可用。
    Registered,
    /// 标识已被占用(携带占用者 user_id)。
    ///
    /// 仅**同租户**冲突携带 `by_user_id`(同信任域,供业务方决定冲突语义)。
    Taken {
        /// 当前占用该标识的用户 ID。
        by_user_id: String,
    },
}

/// 登录标识 Repository trait:`(id_type, id_value)` 为全局主键(数据库唯一约束兜底并发注册),
/// `register` 返回 [`RegisterOutcome`] 供业务方决定冲突语义(拒绝注册 / 引导登录 / 账号合并)。
///
/// # 租户隔离
///
/// 全局主键意味着不同租户无法注册同一标识;冲突命中他租户行时返回中性 `Registered`
///(不带 `by_user_id`,不泄露 user_id),仅同租户冲突返回 `Taken`;租户感知归属查询用 [`find_owner_in_tenant`](Self::find_owner_in_tenant)。
#[async_trait::async_trait]
pub trait UserIdentifierRepository: Send + Sync {
    /// 注册登录标识;`id_value` 由调用方归一化(框架提供 trim,格式校验属业务层)。
    /// INSERT 冲突时按租户作用域回查归属:同租户返回 `Taken { by_user_id }`,他租户占用(或冲突行并发消失)返回中性 `Registered`(不泄露归属)。
    async fn register(
        &self,
        tenant_id: i64,
        id_type: &str,
        id_value: &str,
        user_id: &str,
    ) -> GarrisonResult<RegisterOutcome>;

    /// 查询标识当前归属(**全局**维度,未注册返回 `Ok(None)`)。
    ///
    /// # 泄露警告
    ///
    /// 无租户谓词(全局主键反查原语):调用方必须确保 `id_value` 不来自不可信输入,
    /// 否则返回的 `user_id` 会泄露该标识在**其他租户**的归属;租户上下文场景改用 [`find_owner_in_tenant`](Self::find_owner_in_tenant)。
    async fn find_owner(&self, id_type: &str, id_value: &str) -> GarrisonResult<Option<String>>;

    /// 查询标识在指定租户内的归属(SQL 带 `tenant_id` 谓词,跨租户命中一律 `None`);
    /// 供 `register` 冲突回查与多租户找回密码等租户上下文场景使用。
    async fn find_owner_in_tenant(
        &self,
        tenant_id: i64,
        id_type: &str,
        id_value: &str,
    ) -> GarrisonResult<Option<String>>;
}

/// 单用户最大设备数:`register_device` 在 (tenant_id, login_id) 下设备数达到此值时拒绝新注册。
pub const MAX_DEVICES: usize = 5;

/// 用户设备 Repository trait:设备注册 / 阻断 / 查询;`register_device` 设备数超过 [`MAX_DEVICES`] 时返回 `InvalidParam`,
/// 重复注册同一设备(相同 identifier)幂等返回已有 ID。
#[async_trait::async_trait]
pub trait UserDeviceRepository: Send + Sync {
    /// 注册设备返回设备 ID(UUID):已存在则更新 last_seen_at 返回已有 ID;设备数 >= [`MAX_DEVICES`] 返回 `InvalidParam`。
    ///
    /// # 原子性(MAX_DEVICES 上限)
    ///
    /// 参考实现把「计数检查 + 插入」合并为单条条件 `INSERT ... WHERE (COUNT) < MAX_DEVICES`(消除 check-then-act TOCTOU):
    /// SQLite(单写者)完全原子;PostgreSQL / MySQL 在 READ COMMITTED 下两条并发语句仍可能各按语句级快照同时插入(极小窗口)——
    /// 彻底封死需 DB 级触发器 / 计数约束,DAO 层无跨语句事务 API,在此声明剩余窗口。
    async fn register_device(
        &self,
        tenant_id: i64,
        login_id: &str,
        identifier: &str,
        ua: &str,
    ) -> GarrisonResult<String>;

    /// 阻止设备(is_blocked = 1);必须同时传 `tenant_id` 与 `device_id`——缺租户谓词会构成跨租户封禁原语,跨租户命中 0 行(no-op 幂等)。
    async fn block_device(&self, tenant_id: i64, device_id: &str) -> GarrisonResult<()>;

    /// 解除阻止(is_blocked = 0),租户谓词契约同 [`block_device`](Self::block_device)。
    async fn unblock_device(&self, tenant_id: i64, device_id: &str) -> GarrisonResult<()>;

    /// 列出用户的所有设备(按 tenant_id + login_id 过滤)。
    async fn list_user_devices(
        &self,
        tenant_id: i64,
        login_id: &str,
    ) -> GarrisonResult<Vec<UserDeviceRow>>;

    /// 统计用户设备数。
    async fn count_user_devices(&self, tenant_id: i64, login_id: &str) -> GarrisonResult<usize>;
}

/// WebAuthn 凭据绑定结果:`(tenant_id, credential_id)` 为主键,唯一约束兜底并发;
/// `create` 冲突时回查归属返回 `AlreadyBound`(与登录标识注册同款语义)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WebauthnBindOutcome {
    /// 绑定成功(该凭据此前未被占用)。
    Bound,
    /// 凭据已被绑定(携带占用者 user_id;不泄露其他行内容)。
    AlreadyBound {
        /// 当前占用该凭据的用户 ID。
        by_user_id: String,
    },
}

/// WebAuthn 凭据行(app_webauthn_credential):公钥(COSEKey JSON)、sign_count(克隆检测依据)、
/// backup flags(BE 只升不降 / BS 跟随最新断言)、attestation(可空)。
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct WebauthnCredentialRow {
    /// 租户 ID。
    pub tenant_id: i64,
    /// 绑定用户 ID。
    pub user_id: String,
    /// 凭据 ID(base64url,与 COSE credentialId 一致;主键成分)。
    pub credential_id: String,
    /// 公钥(JSON 序列化的 COSEKey,含算法与坐标)。
    pub public_key: String,
    /// 签名计数器(sign_count;业务层拒绝 count ≤ 上次值的断言——克隆嫌疑)。
    pub sign_count: u32,
    /// 备份资格(backup eligible;只升不降)。
    pub backup_eligible: bool,
    /// 备份状态(backup state;跟随最新断言)。
    pub backup_state: bool,
    /// attestation 格式标识(如 "none" / "packed";可空)。
    pub attestation: Option<String>,
    /// 创建时间(epoch seconds)。
    pub created_at: i64,
    /// 更新时间(epoch seconds)。
    pub updated_at: i64,
}

/// WebAuthn 凭据 Repository trait:绑定(数据库级原子防重)/ 按凭据查询 / 按用户列举 / 认证器状态更新 / 解绑(幂等)。
///
/// 业务不变式(DAO 层不裁决,由 protocol/webauthn service 执行):sign_count 单调(count ≤ 上次 → 克隆嫌疑拒绝);backup_eligible 只升不降。
#[async_trait::async_trait]
pub trait WebauthnCredentialRepository: Send + Sync {
    /// 绑定凭据;`(tenant_id, credential_id)` 冲突时回查归属返回 [`WebauthnBindOutcome::AlreadyBound`](唯一约束兜底并发)。
    async fn create(&self, row: &WebauthnCredentialRow) -> GarrisonResult<WebauthnBindOutcome>;

    /// 按凭据 ID 查询(未绑定返回 `Ok(None)`)。
    async fn find_by_credential_id(
        &self,
        tenant_id: i64,
        credential_id: &str,
    ) -> GarrisonResult<Option<WebauthnCredentialRow>>;

    /// 列出用户全部凭据(按 tenant_id + user_id 过滤)。
    async fn list_by_user(
        &self,
        tenant_id: i64,
        user_id: &str,
    ) -> GarrisonResult<Vec<WebauthnCredentialRow>>;

    /// 更新认证器状态(sign_count / backup flags)并同步刷新 updated_at;凭据不存在返回 `InvalidParam`(不静默吞错)。
    async fn update_authenticator_state(
        &self,
        tenant_id: i64,
        credential_id: &str,
        sign_count: u32,
        backup_eligible: bool,
        backup_state: bool,
    ) -> GarrisonResult<()>;

    /// 解绑凭据(幂等:不存在返回 `Ok(())`)。
    async fn delete(&self, tenant_id: i64, credential_id: &str) -> GarrisonResult<()>;
}

// 密码历史(app_password_history)

/// 密码历史 Repository trait:记录用户历史密码 hash(PHC 字符串),供 `account-policy` 的 `HistoryRule` 拒绝重用最近 N 条;
/// 追加时机:找回密码重置、常规改密与注册路径(host 责任)。
#[async_trait::async_trait]
pub trait PasswordHistoryRepository: Send + Sync {
    /// 追加一条历史 hash(created_at 取当前 epoch 秒)。
    async fn append(
        &self,
        tenant_id: i64,
        user_id: &str,
        password_hash: &str,
    ) -> GarrisonResult<()>;

    /// 取最近 `limit` 条历史 hash(按 created_at 倒序,新在前)。
    async fn recent(
        &self,
        tenant_id: i64,
        user_id: &str,
        limit: u32,
    ) -> GarrisonResult<Vec<String>>;
}

// Dbnexus Repository 实现子模块(db-sqlite / db-postgres / db-mysql 编译;基于 DbPool + sea-orm
// Statement 参数化查询,经 make_statement 运行时占位符转换支持各后端)。
/// Dbnexus Repository 实现子模块(backend-agnostic,支持 SQLite / PostgreSQL / MySQL)。
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub mod sqlite;

/// PostgreSQL Repository 子模块:复用 `sqlite` 的 backend-agnostic 实现(占位符自动转换),仅 re-export 类型别名(详见 `postgres/mod.rs`)。
#[cfg(feature = "db-postgres")]
pub mod postgres;

/// MySQL Repository 子模块:同上复用 `sqlite` 实现,仅 re-export 类型别名(详见 `mysql/mod.rs`)。
#[cfg(feature = "db-mysql")]
pub mod mysql;

/// 角色层级子模块(always compiled:`RoleHierarchyRecord` 不依赖 db-sqlite;`RoleHierarchyService` 依赖 `GarrisonDao` trait)。
pub mod role_hierarchy;

// SQL 方言适配(backend-agnostic 辅助函数);实现见 `dialect`,此处仅模块声明与 re-export。

#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
mod dialect;
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub use dialect::{convert_placeholders, make_statement};

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

    // Row struct 构造测试(验证字段可正确初始化)

    /// UserRow 可构造且字段正确。
    #[test]
    fn user_row_constructs_with_all_fields() {
        let row = UserRow {
            id: "u-001".to_string(),
            username: "alice".to_string(),
            password_hash: "$argon2id$...".to_string(),
            status: "active".to_string(),
            tenant_id: 0,
            created_at: "2026-07-04T00:00:00Z".to_string(),
            updated_at: "2026-07-04T00:00:00Z".to_string(),
            last_login_at: None,
        };
        assert_eq!(row.id, "u-001");
        assert_eq!(row.username, "alice");
        assert_eq!(row.status, "active");
    }

    /// RoleRow 可构造且 is_system 为 false。
    #[test]
    fn role_row_constructs_with_is_system_false() {
        let row = RoleRow {
            id: "r-001".to_string(),
            code: "admin".to_string(),
            name: "Administrator".to_string(),
            description: None,
            tenant_id: 0,
            is_system: false,
            created_at: "2026-07-04T00:00:00Z".to_string(),
            updated_at: "2026-07-04T00:00:00Z".to_string(),
        };
        assert_eq!(row.code, "admin");
        assert!(!row.is_system);
    }

    /// PermissionRow 可构造且无 tenant_id 字段。
    #[test]
    fn permission_row_constructs_without_tenant_id() {
        let row = PermissionRow {
            id: "p-001".to_string(),
            code: "user:read".to_string(),
            name: "Read User".to_string(),
            resource_type: Some("user".to_string()),
            action: Some("read".to_string()),
            created_at: "2026-07-04T00:00:00Z".to_string(),
            updated_at: "2026-07-04T00:00:00Z".to_string(),
        };
        assert_eq!(row.code, "user:read");
    }

    /// UserRoleRow 可构造。
    #[test]
    fn user_role_row_constructs() {
        let row = UserRoleRow {
            user_id: "u-001".to_string(),
            role_id: "r-001".to_string(),
            scope: None,
            grant_time: "2026-07-04T00:00:00Z".to_string(),
            tenant_id: 0,
        };
        assert_eq!(row.user_id, "u-001");
    }

    /// RolePermissionRow 可构造。
    #[test]
    fn role_permission_row_constructs() {
        let row = RolePermissionRow {
            role_id: "r-001".to_string(),
            permission_id: "p-001".to_string(),
            tenant_id: 0,
        };
        assert_eq!(row.role_id, "r-001");
    }

    /// AuthMethodRow 可构造。
    #[test]
    fn auth_method_row_constructs() {
        let row = AuthMethodRow {
            id: "am-001".to_string(),
            user_id: "u-001".to_string(),
            method_type: "password".to_string(),
            external_id: None,
            metadata: None,
            create_time: "2026-07-04T00:00:00Z".to_string(),
            tenant_id: 0,
        };
        assert_eq!(row.method_type, "password");
    }

    /// SessionRow 可构造。
    #[test]
    fn session_row_constructs() {
        let row = SessionRow {
            session_id: "sess-001".to_string(),
            user_id: "u-001".to_string(),
            device_id: Some("web".to_string()),
            ip: Some("127.0.0.1".to_string()),
            user_agent: None,
            login_time: "2026-07-04T00:00:00Z".to_string(),
            last_active: "2026-07-04T00:00:00Z".to_string(),
            expire_time: None,
            tenant_id: 0,
        };
        assert_eq!(row.session_id, "sess-001");
    }

    /// LoginLogRow 可构造且 success 为 true。
    #[test]
    fn login_log_row_constructs_with_success_true() {
        let row = LoginLogRow {
            id: "log-001".to_string(),
            user_id: Some("u-001".to_string()),
            action: "login".to_string(),
            ip: Some("127.0.0.1".to_string()),
            device_id: None,
            success: true,
            fail_reason: None,
            create_time: "2026-07-04T00:00:00Z".to_string(),
            tenant_id: 0,
        };
        assert!(row.success);
        assert_eq!(row.action, "login");
    }

    /// UserExtRow 可构造。
    #[test]
    fn user_ext_row_constructs() {
        let row = UserExtRow {
            id: "ext-001".to_string(),
            user_id: "u-001".to_string(),
            field_key: "email".to_string(),
            field_value: Some("alice@example.com".to_string()),
            field_type: "string".to_string(),
            created_at: "2026-07-04T00:00:00Z".to_string(),
            updated_at: "2026-07-04T00:00:00Z".to_string(),
            tenant_id: 0,
        };
        assert_eq!(row.field_key, "email");
    }

    /// UserDeviceRow 可构造且字段正确。
    #[test]
    fn user_device_row_constructs() {
        let row = UserDeviceRow {
            id: "dev-001".to_string(),
            tenant_id: 42,
            login_id: "1001".to_string(),
            device_identifier: "ua-hash-abc".to_string(),
            device_name: Some("Chrome on Windows".to_string()),
            user_agent: Some("Mozilla/5.0 (Windows NT 10.0)".to_string()),
            is_blocked: false,
            last_seen_at: Some(1750000000),
            created_at: 1749000000,
        };
        assert_eq!(row.id, "dev-001");
        assert_eq!(row.tenant_id, 42);
        assert_eq!(row.login_id, "1001");
        assert_eq!(row.device_identifier, "ua-hash-abc");
        assert!(!row.is_blocked);
    }

    /// MAX_DEVICES 常量值为 5。
    #[test]
    fn max_devices_is_five() {
        assert_eq!(MAX_DEVICES, 5);
    }

    // New* struct 构造测试

    /// NewUser 可构造。
    #[test]
    fn new_user_constructs() {
        let new = NewUser {
            username: "alice".to_string(),
            password_hash: "$argon2id$...".to_string(),
            status: "active".to_string(),
        };
        assert_eq!(new.username, "alice");
    }

    /// NewRole 可构造。
    #[test]
    fn new_role_constructs() {
        let new = NewRole {
            code: "admin".to_string(),
            name: "Administrator".to_string(),
            description: None,
            is_system: false,
        };
        assert_eq!(new.code, "admin");
    }

    /// NewPermission 可构造。
    #[test]
    fn new_permission_constructs() {
        let new = NewPermission {
            code: "user:read".to_string(),
            name: "Read User".to_string(),
            resource_type: Some("user".to_string()),
            action: Some("read".to_string()),
        };
        assert_eq!(new.code, "user:read");
    }

    /// NewAuthMethod 可构造。
    #[test]
    fn new_auth_method_constructs() {
        let new = NewAuthMethod {
            user_id: "u-001".to_string(),
            method_type: "password".to_string(),
            external_id: None,
            metadata: None,
        };
        assert_eq!(new.method_type, "password");
    }

    /// NewSession 可构造。
    #[test]
    fn new_session_constructs() {
        let new = NewSession {
            session_id: "sess-001".to_string(),
            user_id: "u-001".to_string(),
            device_id: Some("web".to_string()),
            ip: None,
            user_agent: None,
            expire_time: None,
        };
        assert_eq!(new.session_id, "sess-001");
    }

    /// NewLoginLog 可构造。
    #[test]
    fn new_login_log_constructs() {
        let new = NewLoginLog {
            user_id: Some("u-001".to_string()),
            action: "login".to_string(),
            ip: None,
            device_id: None,
            success: true,
            fail_reason: None,
        };
        assert_eq!(new.action, "login");
    }

    /// UpdateUser 可构造且默认全 None。
    #[test]
    fn update_user_default_all_none() {
        let update = UpdateUser::default();
        assert!(update.username.is_none());
        assert!(update.password_hash.is_none());
        assert!(update.status.is_none());
        assert!(update.last_login_at.is_none());
    }

    // Row struct 序列化测试(验证 Serialize/Deserialize 派生)

    /// UserRow 可序列化为 JSON 且可反序列化。
    #[test]
    fn user_row_serializes_and_deserializes() {
        let row = UserRow {
            id: "u-001".to_string(),
            username: "alice".to_string(),
            password_hash: "$argon2id$...".to_string(),
            status: "active".to_string(),
            tenant_id: 0,
            created_at: "2026-07-04T00:00:00Z".to_string(),
            updated_at: "2026-07-04T00:00:00Z".to_string(),
            last_login_at: None,
        };
        let json = serde_json::to_string(&row).unwrap();
        let deserialized: UserRow = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.id, "u-001");
        assert_eq!(deserialized.username, "alice");
    }

    /// PermissionRow 可序列化且无 tenant_id 字段。
    #[test]
    fn permission_row_serializes_without_tenant_id() {
        let row = PermissionRow {
            id: "p-001".to_string(),
            code: "user:read".to_string(),
            name: "Read User".to_string(),
            resource_type: None,
            action: None,
            created_at: "2026-07-04T00:00:00Z".to_string(),
            updated_at: "2026-07-04T00:00:00Z".to_string(),
        };
        let json = serde_json::to_string(&row).unwrap();
        assert!(
            !json.contains("tenant_id"),
            "PermissionRow JSON 不应包含 tenant_id"
        );
    }

    // trait Send + Sync 编译期检查

    /// 所有 Repository trait 为 Send + Sync(编译期检查;`?Sized` 允许 `dyn Trait` 作类型参数)。
    #[test]
    fn all_repository_traits_are_send_sync() {
        fn assert_send_sync<T: Send + Sync + ?Sized>() {}
        // 仅验证 trait 本身满足 Send + Sync;具体 impl 由各后端实现的测试验证
        assert_send_sync::<dyn UserRepository>();
        assert_send_sync::<dyn RoleRepository>();
        assert_send_sync::<dyn PermissionRepository>();
        assert_send_sync::<dyn UserRoleRepository>();
        assert_send_sync::<dyn RolePermissionRepository>();
        assert_send_sync::<dyn AuthMethodRepository>();
        assert_send_sync::<dyn SessionRepository>();
        assert_send_sync::<dyn LoginLogRepository>();
        assert_send_sync::<dyn UserExtRepository>();
        assert_send_sync::<dyn UserDeviceRepository>();
    }

    // PostgreSQL 后端集成测试(#[ignore],需 DATABASE_URL 指向真实 PG)

    /// 验证 DbnexusUserRepository 在 PostgreSQL 下 find_by_id 正确执行(含 `?` → `$1, $2` 占位符转换);流程:建表 → 插入 → 查询 → 清理。
    /// 运行:`DATABASE_URL=postgres://... cargo test --features db-postgres --lib -- --ignored`。
    #[cfg(feature = "db-postgres")]
    #[tokio::test(flavor = "multi_thread")]
    #[serial_test::serial]
    #[ignore = "需要真实 PostgreSQL,设置 DATABASE_URL 后 cargo test -- --ignored 运行"]
    async fn dbnexus_user_repository_works_with_postgres_backend() {
        use crate::dao::init_dbnexus;
        use crate::dao::repository::sqlite::DbnexusUserRepository;
        use dbnexus::sea_orm::ConnectionTrait;

        let database_url = std::env::var("DATABASE_URL").unwrap_or_else(|_| {
            panic!("DATABASE_URL 未设置,请指向 PostgreSQL 连接字符串");
        });

        // 初始化 PostgreSQL 连接池
        let pool = init_dbnexus(&database_url)
            .await
            .expect("初始化 PostgreSQL 连接池失败");

        // 建表:PostgreSQL 兼容 DDL,BIGINT 匹配 i64
        {
            let session = pool.get_session("admin").await.expect("获取 session 失败");
            let conn = session.connection().expect("获取 connection 失败");
            // 清理残留表(按依赖逆序)
            let _ = conn
                .execute_unprepared("DROP TABLE IF EXISTS app_user_ext")
                .await;
            let _ = conn
                .execute_unprepared("DROP TABLE IF EXISTS app_login_log")
                .await;
            let _ = conn
                .execute_unprepared("DROP TABLE IF EXISTS app_session")
                .await;
            let _ = conn
                .execute_unprepared("DROP TABLE IF EXISTS app_auth_method")
                .await;
            let _ = conn
                .execute_unprepared("DROP TABLE IF EXISTS app_role_permission")
                .await;
            let _ = conn
                .execute_unprepared("DROP TABLE IF EXISTS app_user_role")
                .await;
            let _ = conn
                .execute_unprepared("DROP TABLE IF EXISTS app_permission")
                .await;
            let _ = conn
                .execute_unprepared("DROP TABLE IF EXISTS app_role")
                .await;
            let _ = conn
                .execute_unprepared("DROP TABLE IF EXISTS app_user")
                .await;
            conn.execute_unprepared(
                "CREATE TABLE app_user (
                    id              TEXT    PRIMARY KEY,
                    username        TEXT    NOT NULL,
                    password_hash   TEXT    NOT NULL,
                    status          TEXT    NOT NULL DEFAULT 'pending',
                    tenant_id       BIGINT  NOT NULL DEFAULT 0,
                    created_at      TEXT    NOT NULL DEFAULT CURRENT_TIMESTAMP,
                    updated_at      TEXT    NOT NULL DEFAULT CURRENT_TIMESTAMP,
                    last_login_at   TEXT
                )",
            )
            .await
            .expect("创建 app_user 表失败");
        }

        let repo = DbnexusUserRepository::new(pool.clone());

        let tenant_id: i64 = 42;
        let user_id = repo
            .create(
                tenant_id,
                NewUser {
                    username: "pg-test-user".to_string(),
                    password_hash: "$argon2id$m=8,t=1,p=1$fake-hash".to_string(),
                    status: "active".to_string(),
                },
            )
            .await
            .expect("插入测试用户失败");

        // 验证占位符转换(? → $1, $2 在真实 PG 上执行)
        let found = repo
            .find_by_id(tenant_id, &user_id)
            .await
            .expect("find_by_id 查询失败")
            .expect("测试用户未找到");

        assert_eq!(found.id, user_id);
        assert_eq!(found.username, "pg-test-user");
        assert_eq!(found.password_hash, "$argon2id$m=8,t=1,p=1$fake-hash");
        assert_eq!(found.status, "active");
        assert_eq!(found.tenant_id, tenant_id);

        repo.delete(tenant_id, &user_id)
            .await
            .expect("清理测试数据失败");

        // 删除手动建的表:本测试不经迁移器建表,残留会使 run_embedded_postgres 的 001_init 撞「表已存在」
        //(两个 postgres 集成测试共用 DATABASE_URL,#[serial] 串行,先后顺序均可)。
        {
            let session = pool.get_session("admin").await.expect("获取 session 失败");
            let conn = session.connection().expect("获取 connection 失败");
            conn.execute_unprepared("DROP TABLE IF EXISTS app_user")
                .await
                .expect("清理 app_user 表失败");
        }
    }
}