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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! dbnexus 集成模块(对应二级持久化层):经 dbnexus 提供 SQLite/PostgreSQL/MySQL 连接池、Session、迁移能力。
//!
//! 不定义自有 DB trait,直接复用 `dbnexus::DbPool`:`init_dbnexus(url)` 返回 `DbPool`;
//! `GarrisonMigration` 包装 `DbPool::run_migrations`,按 spec 分层管理迁移脚本。

use crate::error::{GarrisonError, GarrisonResult};
use dbnexus::DbPool;
use std::path::{Path, PathBuf};

/// 编译时嵌入的 postgres 迁移目录(`include_dir!` 嵌入二进制,`embedded-migrations` feature 可用)。
/// 配合 [`GarrisonMigration::run_embedded_postgres`],crates.io 消费者无需访问 garrison 源码目录即可执行 postgres schema 迁移。
#[cfg(feature = "embedded-migrations")]
static POSTGRES_MIGRATIONS: include_dir::Dir<'_> = include_dir::include_dir!("migrations/postgres");

/// 初始化 dbnexus 连接池(最常用入口)。`url` 示例:`sqlite::memory:`(内存)/ `sqlite:///path/to/db.sqlite`(文件)。
///
/// # 示例
/// ```ignore
/// use garrison::dao::init_dbnexus;
/// let pool = init_dbnexus("sqlite::memory:").await?;
/// ```
pub async fn init_dbnexus(url: &str) -> GarrisonResult<DbPool> {
    DbPool::new(url)
        .await
        .map_err(|e| GarrisonError::Dao(format!("dao-dbnexus-init::{}", e)))
}
/// 初始化 dbnexus 连接池(显式 `PoolConfig`:最大/最小连接数、空闲超时、获取超时),
/// 替代 `DbPool::new` 的库默认值(max=20/min=5);需 failover/副本等完整配置可直接用 dbnexus `DbPool::builder` + `FailoverConfig`。
///
/// # 示例
/// ```ignore
/// use garrison::dao::init_dbnexus_with_pool_config;
/// use dbnexus::PoolConfig;
///
/// let pool = init_dbnexus_with_pool_config(
/// "postgres://localhost/app",
/// PoolConfig { max_connections: 50, ..Default::default() },
/// ).await?;
/// ```
pub async fn init_dbnexus_with_pool_config(
    url: &str,
    pool_config: dbnexus::PoolConfig,
) -> GarrisonResult<DbPool> {
    let db_config = dbnexus::DbConfig {
        url: url.to_string(),
        pool_config,
        ..Default::default()
    };
    dbnexus::DbPoolBuilder::new()
        .config(db_config)
        .build()
        .await
        .map_err(|e| GarrisonError::Dao(format!("dao-dbnexus-init-pool::{}", e)))
}

/// Garrison schema 迁移管理器:包装 `DbPool::run_migrations`,按 extensible-schema spec 分层
///(`migrate_core` = `core/*.sql`(8 张核心表 + app_user_ext)、`migrate_extensions` = `extensions/*.sql`、
/// `migrate_tenant` = `tenant/*.sql`;`run_all()` 按 core→extensions→tenant 顺序执行)。
///
/// 迁移文件命名 `{version}_{description}.sql`(如 `001_init.sql`),内容用 `-- UP:` / `-- DOWN:` 分隔。
///
/// # 版本号全局唯一约束
/// dbnexus 历史表按 version 全局去重(不区分目录),跨目录版本号必须互不冲突:
/// `core/` 1–999(随版本发布)/`extensions/` 1000+/`tenant/` 2000+。
pub struct GarrisonMigration {
    pool: DbPool,
    base_dir: PathBuf,
}

impl GarrisonMigration {
    /// 创建迁移管理器,使用默认 `migrations/sqlite/` 基目录。
    pub fn new(pool: DbPool) -> Self {
        Self::with_base_dir(pool, PathBuf::from("migrations/sqlite"))
    }

    /// 创建迁移管理器,指定基目录(用于测试或自定义路径)。
    pub fn with_base_dir(pool: DbPool, base_dir: PathBuf) -> Self {
        Self { pool, base_dir }
    }

    /// 获取底层 `DbPool` 引用(用于查询、Session 等操作)。
    pub fn pool(&self) -> &DbPool {
        &self.pool
    }

    /// 执行核心表迁移(`{base_dir}/core/*.sql`)。
    ///
    /// 对应 extensible-schema spec:8 张核心表 + app_user_ext。
    pub async fn migrate_core(&self) -> GarrisonResult<u32> {
        self.run_dir(&self.base_dir.join("core")).await
    }

    /// 执行扩展表迁移(`{base_dir}/extensions/*.sql`)。
    ///
    /// 对应 extensible-schema spec:用户自定义扩展表(如表名以 `app_` 前缀)。
    pub async fn migrate_extensions(&self) -> GarrisonResult<u32> {
        self.run_dir(&self.base_dir.join("extensions")).await
    }

    /// 执行多租户表迁移(`{base_dir}/tenant/*.sql`)。
    ///
    /// 对应 extensible-schema spec:多租户特定表。
    pub async fn migrate_tenant(&self) -> GarrisonResult<u32> {
        self.run_dir(&self.base_dir.join("tenant")).await
    }

    /// 一次性按 core→extensions→tenant 顺序执行所有迁移(任一阶段失败立即返回错误,不继续后续阶段)。
    pub async fn run_all(&self) -> GarrisonResult<u32> {
        let mut total = 0;
        total += self.migrate_core().await?;
        total += self.migrate_extensions().await?;
        total += self.migrate_tenant().await?;
        Ok(total)
    }

    /// 执行嵌入的 postgres 迁移(不需文件系统访问):把 `include_dir!` 嵌入内容写到临时目录后调 `DbPool::run_migrations`,
    /// 完全复用 dbnexus 的迁移历史记录、版本过滤与事务逻辑;适用于 crates.io 消费者(运行时工作目录无 `migrations/postgres/`)。
    ///
    /// # 子目录遍历
    ///
    /// dbnexus `scan_migrations` 只扫指定目录顶层 `.sql`、**不递归子目录**;本方法遍历 `temp_dir` 的每个子目录
    /// 独立调 `GarrisonMigration::run_dir`(`copy_embedded_dir` 保留 `core/` 等结构),未来新增子目录无需改动。
    ///
    /// # Errors
    ///
    /// 临时目录创建 / 嵌入文件写入 / 目录读取 / dbnexus 迁移执行(SQL 语法、版本冲突等)失败均返回 [`GarrisonError::Dao`]。
    #[cfg(feature = "embedded-migrations")]
    pub async fn run_embedded_postgres(&self) -> GarrisonResult<u32> {
        let temp_dir = tempfile::tempdir()
            .map_err(|e| GarrisonError::Dao(format!("embedded-migrations-tempdir::{e}")))?;

        // 将嵌入的 postgres 迁移文件写到临时目录(保留 core/ 等子目录结构)
        copy_embedded_dir(&POSTGRES_MIGRATIONS, temp_dir.path())
            .map_err(|e| GarrisonError::Dao(format!("embedded-migrations-write::{e}")))?;

        // dbnexus scan_migrations 不递归子目录,需遍历 temp_dir 的子目录逐个执行。
        // garrison postgres 迁移按 core/extensions/tenant 分层(版本号全局唯一),
        // 对每个子目录独立调用 run_dir,累积应用迁移数。
        let mut total = 0;
        let entries = std::fs::read_dir(temp_dir.path())
            .map_err(|e| GarrisonError::Dao(format!("embedded-migrations-readdir::{e}")))?;
        for entry in entries {
            let entry = entry
                .map_err(|e| GarrisonError::Dao(format!("embedded-migrations-direntry::{e}")))?;
            let path = entry.path();
            if path.is_dir() {
                total += self.run_dir(&path).await?;
            }
        }
        Ok(total)
    }

    /// 执行指定目录的迁移文件;不存在的目录返回 0(符合 dbnexus scan_migrations 行为)。
    async fn run_dir(&self, dir: &Path) -> GarrisonResult<u32> {
        self.pool.run_migrations(dir).await.map_err(|e| {
            GarrisonError::Dao(format!("dao-dbnexus-migrate::{}::{}", dir.display(), e))
        })
    }
}

/// 递归复制 `include_dir::Dir` 到文件系统目标目录(供 [`GarrisonMigration::run_embedded_postgres`] 展开嵌入迁移树,含 `core/` 子目录)。
///
/// `include_dir::DirEntry::File::path()` 返回相对**根嵌入目录**的路径(如 `core/001_init.sql`),
/// 递归处理子目录时必须只取 `file_name()`,否则会重复创建 `core/core/` 嵌套目录。
///
/// # Errors
///
/// 返回 `std::io::Error` 的场景:
/// - 创建目录失败(权限不足、路径无效等)
/// - 写入文件失败(磁盘满、路径无效等)
#[cfg(feature = "embedded-migrations")]
fn copy_embedded_dir(dir: &include_dir::Dir, dest: &std::path::Path) -> std::io::Result<()> {
    std::fs::create_dir_all(dest)?;
    for entry in dir.entries() {
        match entry {
            include_dir::DirEntry::Dir(sub_dir) => {
                let sub_dest = dest.join(sub_dir.path().file_name().unwrap_or_else(|| {
                    panic!("embedded migration subdirectory must have valid name")
                }));
                copy_embedded_dir(sub_dir, &sub_dest)?;
            },
            include_dir::DirEntry::File(file) => {
                // file.path() 返回相对于根的路径(如 "core/001_init.sql"),
                // 递归到子目录时只取 file_name 避免 core/core/ 嵌套
                let file_name = file
                    .path()
                    .file_name()
                    .expect("embedded migration file must have valid name");
                let file_dest = dest.join(file_name);
                std::fs::write(&file_dest, file.contents())?;
            },
        }
    }
    Ok(())
}

#[cfg(all(test, feature = "db-sqlite"))]
mod tests {
    use super::*;
    use dbnexus::sea_orm::{ConnectionTrait, DbBackend, Statement};

    // init_dbnexus 辅助函数测试

    /// 验证 init_dbnexus 用 sqlite::memory: 创建池成功。
    #[tokio::test]
    async fn init_dbnexus_sqlite_memory() {
        let pool = init_dbnexus("sqlite::memory:").await;
        assert!(
            pool.is_ok(),
            "init_dbnexus sqlite::memory: 应成功: {:?}",
            pool.err()
        );
    }
    /// 验证 init_dbnexus_with_pool_config 走 DbPoolBuilder 通路创建池成功,
    /// 且可执行查询(连接池真实可用)。
    #[tokio::test]
    async fn init_dbnexus_with_pool_config_sqlite_memory() {
        use dbnexus::PoolConfig;
        let pool = init_dbnexus_with_pool_config(
            "sqlite::memory:",
            PoolConfig {
                max_connections: 2,
                min_connections: 1,
                ..Default::default()
            },
        )
        .await
        .expect("init_dbnexus_with_pool_config 应成功");
        let session = pool.get_session("admin").await.expect("应能获取会话");
        session
            .execute_raw_ddl("CREATE TABLE test_pool_cfg (v INTEGER)")
            .await
            .expect("CREATE TABLE 应成功");
        session
            .execute_raw("INSERT INTO test_pool_cfg (v) VALUES (42)")
            .await
            .expect("INSERT 应成功");
        let rows = session
            .query_rows("SELECT v FROM test_pool_cfg")
            .await
            .expect("查询应成功");
        assert_eq!(rows[0]["v"].as_i64(), Some(42), "池应真实可用");
    }

    /// 验证 init_dbnexus 用无效 URL 返回错误(Fail Loud 原则)。
    #[tokio::test]
    async fn init_dbnexus_invalid_url_errors() {
        let result = init_dbnexus("not-a-valid-url").await;
        assert!(
            matches!(result, Err(GarrisonError::Dao(_))),
            "无效 URL 应返回 Dao 错误,实际: {:?}",
            result.map(|_| ())
        );
    }

    // GarrisonMigration 测试(使用临时目录 + sqlite::memory:)

    /// 验证 migrate_core 在空目录上返回 0。
    #[tokio::test]
    async fn migrate_core_empty_dir_returns_zero() {
        let pool = init_dbnexus("sqlite::memory:").await.unwrap();
        let tmp = tempfile::tempdir().unwrap();
        // 不创建 core/ 目录,run_dir 应返回 0
        let migration = GarrisonMigration::with_base_dir(pool, tmp.path().to_path_buf());
        let result = migration.migrate_core().await;
        assert!(result.is_ok(), "空目录迁移应成功: {:?}", result.err());
        assert_eq!(result.unwrap(), 0);
    }

    /// 验证 migrate_core 执行单个 SQL 文件后返回 1。
    #[tokio::test]
    async fn migrate_core_single_file() {
        let pool = init_dbnexus("sqlite::memory:").await.unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let core_dir = tmp.path().join("core");
        std::fs::create_dir_all(&core_dir).unwrap();
        std::fs::write(
            core_dir.join("001_init.sql"),
            "-- UP:\nCREATE TABLE test_table (id INTEGER PRIMARY KEY, name TEXT);\n-- DOWN:\nDROP TABLE test_table;\n",
        )
        .unwrap();

        let migration = GarrisonMigration::with_base_dir(pool, tmp.path().to_path_buf());
        let applied = migration.migrate_core().await.unwrap();
        assert_eq!(applied, 1, "应执行 1 个迁移文件");

        // 再次执行应返回 0(幂等性)
        // 注意:内存数据库每次 run_migrations 会重新扫描,但 dbnexus_migrations 表记录了已应用版本
        // 此处不重复执行(避免复杂化),由后续集成测试覆盖幂等性
    }

    /// 验证 run_all 按顺序执行 core/extensions/tenant。
    ///
    /// 注意:dbnexus 版本号全局唯一(不区分目录)——core/001_init.sql=1、extensions/1000_ext.sql=1000、tenant/2000_tenant.sql=2000。
    #[tokio::test]
    async fn run_all_executes_in_order() {
        let pool = init_dbnexus("sqlite::memory:").await.unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let base = tmp.path();

        // core: 001_init.sql (version=1)
        let core_dir = base.join("core");
        std::fs::create_dir_all(&core_dir).unwrap();
        std::fs::write(
            core_dir.join("001_init.sql"),
            "-- UP:\nCREATE TABLE core_t (id INTEGER PRIMARY KEY);\n",
        )
        .unwrap();

        // extensions: 1000_ext.sql (version=1000)
        let ext_dir = base.join("extensions");
        std::fs::create_dir_all(&ext_dir).unwrap();
        std::fs::write(
            ext_dir.join("1000_ext.sql"),
            "-- UP:\nCREATE TABLE ext_t (id INTEGER PRIMARY KEY);\n",
        )
        .unwrap();

        // tenant: 2000_tenant.sql (version=2000)
        let tenant_dir = base.join("tenant");
        std::fs::create_dir_all(&tenant_dir).unwrap();
        std::fs::write(
            tenant_dir.join("2000_tenant.sql"),
            "-- UP:\nCREATE TABLE tenant_t (id INTEGER PRIMARY KEY);\n",
        )
        .unwrap();

        let migration = GarrisonMigration::with_base_dir(pool, base.to_path_buf());
        let total = migration.run_all().await.unwrap();
        assert_eq!(total, 3, "run_all 应执行 3 个迁移文件");
    }

    /// 验证 GarrisonMigration::new 使用默认 base_dir。
    #[tokio::test]
    async fn new_uses_default_base_dir() {
        let pool = init_dbnexus("sqlite::memory:").await.unwrap();
        let migration = GarrisonMigration::new(pool);
        assert_eq!(migration.base_dir, PathBuf::from("migrations/sqlite"));
    }

    // CRUD 测试:验证 Session execute_raw_ddl / execute_raw / query

    /// 辅助函数:查询单行单列字符串值。
    async fn query_one_string(session: &dbnexus::Session, sql: &str) -> String {
        let conn = session
            .connection()
            .expect("connection should be available");
        let stmt = Statement::from_sql_and_values(DbBackend::Sqlite, sql, vec![]);
        let row = conn
            .query_one_raw(stmt)
            .await
            .expect("query_one should succeed")
            .expect("row should exist");
        row.try_get::<String>("", "val")
            .expect("column 'val' should be present")
    }

    /// 辅助函数:查询 count(*) 结果。
    async fn query_count(session: &dbnexus::Session, sql: &str) -> i64 {
        let conn = session
            .connection()
            .expect("connection should be available");
        let stmt = Statement::from_sql_and_values(DbBackend::Sqlite, sql, vec![]);
        let row = conn
            .query_one_raw(stmt)
            .await
            .expect("query_one should succeed")
            .expect("row should exist");
        row.try_get::<i64>("", "cnt")
            .expect("column 'cnt' should be present")
    }

    /// CRUD 完整流程:CREATE TABLE → INSERT → SELECT → UPDATE → SELECT → DELETE → SELECT,各步 rows_affected 与结果符合预期。
    #[tokio::test]
    async fn dbnexus_crud_full_cycle() {
        let pool = init_dbnexus("sqlite::memory:").await.unwrap();
        let session = pool.get_session("admin").await.unwrap();

        // CREATE TABLE(DDL 用 execute_raw_ddl,execute_raw 会拒绝 DDL)
        session
            .execute_raw_ddl("CREATE TABLE test_crud (id INTEGER PRIMARY KEY, name TEXT NOT NULL)")
            .await
            .expect("CREATE TABLE 应成功");

        let result = session
            .execute_raw("INSERT INTO test_crud (id, name) VALUES (1, 'alice')")
            .await
            .expect("INSERT 应成功");
        assert_eq!(result.rows_affected(), 1, "INSERT 应影响 1 行");

        let name =
            query_one_string(&session, "SELECT name AS val FROM test_crud WHERE id = 1").await;
        assert_eq!(name, "alice", "INSERT 后应查到 alice");

        let result = session
            .execute_raw("UPDATE test_crud SET name = 'bob' WHERE id = 1")
            .await
            .expect("UPDATE 应成功");
        assert_eq!(result.rows_affected(), 1, "UPDATE 应影响 1 行");

        let name =
            query_one_string(&session, "SELECT name AS val FROM test_crud WHERE id = 1").await;
        assert_eq!(name, "bob", "UPDATE 后应查到 bob");

        let result = session
            .execute_raw("DELETE FROM test_crud WHERE id = 1")
            .await
            .expect("DELETE 应成功");
        assert_eq!(result.rows_affected(), 1, "DELETE 应影响 1 行");

        let count = query_count(&session, "SELECT count(*) AS cnt FROM test_crud").await;
        assert_eq!(count, 0, "DELETE 后表应为空");
    }

    // 事务测试:验证 begin/commit/rollback

    /// 事务回滚后未提交的数据不可见(count == 0)。
    #[tokio::test]
    async fn dbnexus_transaction_rollback() {
        let pool = init_dbnexus("sqlite::memory:").await.unwrap();
        let session = pool.get_session("admin").await.unwrap();

        session
            .execute_raw_ddl("CREATE TABLE test_txn (id INTEGER PRIMARY KEY, name TEXT)")
            .await
            .unwrap();

        session.begin_transaction().await.expect("begin 应成功");

        session
            .execute_raw("INSERT INTO test_txn (id, name) VALUES (1, 'temp')")
            .await
            .expect("事务内 INSERT 应成功");

        // 回滚
        session.rollback().await.expect("rollback 应成功");

        let count = query_count(&session, "SELECT count(*) AS cnt FROM test_txn").await;
        assert_eq!(count, 0, "回滚后表应为空");
    }

    /// 事务提交后数据持久化(count == 1)。
    #[tokio::test]
    async fn dbnexus_transaction_commit() {
        let pool = init_dbnexus("sqlite::memory:").await.unwrap();
        let session = pool.get_session("admin").await.unwrap();

        session
            .execute_raw_ddl("CREATE TABLE test_txn_c (id INTEGER PRIMARY KEY, name TEXT)")
            .await
            .unwrap();

        session.begin_transaction().await.unwrap();
        session
            .execute_raw("INSERT INTO test_txn_c (id, name) VALUES (1, 'committed')")
            .await
            .unwrap();
        session.commit().await.expect("commit 应成功");

        let count = query_count(&session, "SELECT count(*) AS cnt FROM test_txn_c").await;
        assert_eq!(count, 1, "提交后应有 1 条记录");
    }

    // 8 表验证测试:用项目根目录的 migrations/sqlite/core/001_init.sql

    /// migrate_core 创建 8 张核心表 + app_user_ext:sqlite_master 应含 10 张表——
    /// app_user / app_role / app_permission / app_user_role / app_role_permission / app_auth_method / app_session / app_login_log / app_user_ext / app_user_device。
    #[tokio::test]
    async fn migrate_core_creates_all_core_tables() {
        let pool = init_dbnexus("sqlite::memory:").await.unwrap();

        // 用 CARGO_MANIFEST_DIR 定位项目根目录的 migrations/sqlite/
        let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR 应可用");
        let base_dir = PathBuf::from(manifest_dir).join("migrations/sqlite");

        let migration = GarrisonMigration::with_base_dir(pool, base_dir);
        let applied = migration.migrate_core().await.expect("migrate_core 应成功");
        // 001_init.sql + 002_role_hierarchy.sql + 003_refresh_tokens.sql + 004_audit_logs.sql = 4 个文件
        assert!(
            applied >= 4,
            "应至少执行 4 个迁移文件(001-004),实际: {}",
            applied
        );

        let pool = migration.pool();
        let session = pool.get_session("admin").await.unwrap();
        let conn = session.connection().unwrap();
        let stmt = Statement::from_sql_and_values(
            DbBackend::Sqlite,
            "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name",
            vec![],
        );
        let rows = conn.query_all_raw(stmt).await.expect("query_all 应成功");
        let table_names: Vec<String> = rows
            .iter()
            .map(|row| row.try_get::<String>("", "name").unwrap_or_default())
            .collect();

        // 8 张核心表 + app_user_ext + app_user_device = 10 张表
        // (不含 dbnexus_migrations / role_hierarchy / refresh_tokens / audit_logs)
        let expected_tables = [
            "app_auth_method",
            "app_login_log",
            "app_permission",
            "app_role",
            "app_role_permission",
            "app_session",
            "app_user",
            "app_user_device",
            "app_user_ext",
            "app_user_role",
            "app_password_history",
        ];
        for expected in &expected_tables {
            assert!(
                table_names.contains(&expected.to_string()),
                "核心表 {} 应存在于 sqlite_master,实际表: {:?}",
                expected,
                table_names
            );
        }
        assert_eq!(
            expected_tables.len(),
            11,
            "应有 11 张核心表(8 核心 + app_user_ext + app_user_device + app_password_history)"
        );
    }

    /// 迁移幂等性:重复 migrate_core 第二次返回 0(无新增迁移),10 张表仍存在。
    #[tokio::test]
    async fn migrate_core_idempotent() {
        let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
        let base_dir = PathBuf::from(manifest_dir).join("migrations/sqlite");

        let pool = init_dbnexus("sqlite::memory:").await.unwrap();
        let migration = GarrisonMigration::with_base_dir(pool, base_dir);

        // 第一次:应用迁移(001-006 共 6 个文件)
        let first = migration
            .migrate_core()
            .await
            .expect("第一次 migrate 应成功");
        assert!(
            first >= 4,
            "第一次应至少执行 4 个迁移(001-006),实际: {}",
            first
        );

        // 第二次:应跳过(已应用)
        let second = migration
            .migrate_core()
            .await
            .expect("第二次 migrate 应成功");
        assert_eq!(second, 0, "第二次应跳过已应用的迁移");

        let pool = migration.pool();
        let session = pool.get_session("admin").await.unwrap();
        let count = query_count(
            &session,
            "SELECT count(*) AS cnt FROM sqlite_master WHERE type='table' AND name LIKE 'app_%'",
        )
        .await;
        assert_eq!(
            count, 13,
            "应有 13 张 app_ 前缀的表(012 新增 app_user_identifier,014 新增 app_webauthn_credential,016 新增 app_password_history)"
        );
    }

    /// 迁移后 app_user 表可正常 CRUD(端到端验证)。
    #[tokio::test]
    async fn app_user_table_crud_after_migration() {
        let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
        let base_dir = PathBuf::from(manifest_dir).join("migrations/sqlite");

        let pool = init_dbnexus("sqlite::memory:").await.unwrap();
        let migration = GarrisonMigration::with_base_dir(pool, base_dir);
        migration.migrate_core().await.expect("migrate 应成功");

        let pool = migration.pool();
        let session = pool.get_session("admin").await.unwrap();

        session
            .execute_raw(
                "INSERT INTO app_user (id, username, password_hash, status, tenant_id) \
                 VALUES ('u-001', 'alice', 'argon2$hash', 'active', 0)",
            )
            .await
            .expect("INSERT app_user 应成功");

        let username = query_one_string(
            &session,
            "SELECT username AS val FROM app_user WHERE id = 'u-001'",
        )
        .await;
        assert_eq!(username, "alice", "应查到 alice");

        let status = query_one_string(
            &session,
            "SELECT status AS val FROM app_user WHERE id = 'u-001'",
        )
        .await;
        assert_eq!(status, "active", "status 应为 active");
    }
}

/// 嵌入式 postgres 迁移测试模块:独立门控于 `db-postgres`(embedded-migrations 由其透传启用),
/// 不与 `#[cfg(all(test, feature = "db-sqlite"))]` 的 tests 模块混合,避免 feature cfg 冲突。
#[cfg(all(test, feature = "embedded-migrations"))]
mod embedded_migrations_tests {
    use super::*;

    // 单元测试(不需数据库,验证 include_dir! 嵌入与文件写入逻辑)

    /// 验证 POSTGRES_MIGRATIONS 嵌入了 core 目录且含 16 个 .sql(001_init ~ 017_oauth2_backchannel_queue,含 013_refresh_tokens_rotated_at 与 016_password_history;015 为并行段预留编号)。
    #[test]
    fn embedded_postgres_migrations_contain_15_core_files() {
        let core_dir = POSTGRES_MIGRATIONS
            .get_dir("core")
            .expect("migrations/postgres/core 必须被嵌入");
        let sql_files: Vec<_> = core_dir
            .files()
            .filter(|f| f.path().extension().is_some_and(|ext| ext == "sql"))
            .collect();
        assert_eq!(
            sql_files.len(),
            16,
            "postgres core 迁移必须有 16 个 SQL 文件,实际: {sql_files:?}"
        );
        // 验证文件名边界(按版本号约定)
        let names: Vec<String> = sql_files
            .iter()
            .filter_map(|f| {
                f.path()
                    .file_name()
                    .and_then(|n| n.to_str())
                    .map(String::from)
            })
            .collect();
        assert!(
            names.iter().any(|n| n.starts_with("001_")),
            "必须包含 001_init.sql,实际: {names:?}"
        );
        assert!(
            names.iter().any(|n| n.starts_with("006_")),
            "必须包含 006_user_devices.sql,实际: {names:?}"
        );
        assert!(
            names
                .iter()
                .any(|n| n.starts_with("007_refresh_tokens_oauth2_fields")),
            "必须包含 007_refresh_tokens_oauth2_fields.sql,实际: {names:?}"
        );
        assert!(
            names
                .iter()
                .any(|n| n.starts_with("017_oauth2_backchannel_queue")),
            "必须包含 017_oauth2_backchannel_queue.sql,实际: {names:?}"
        );
        assert!(
            names
                .iter()
                .any(|n| n.starts_with("013_refresh_tokens_rotated_at")),
            "必须包含 013_refresh_tokens_rotated_at.sql,实际: {names:?}"
        );
        assert!(
            names.iter().any(|n| n.starts_with("016_password_history")),
            "必须包含 016_password_history.sql,实际: {names:?}"
        );
    }

    /// 验证 copy_embedded_dir 递归写入临时目录:tempdir/core/ 含 16 个 .sql 且内容与嵌入文件一致。
    #[test]
    fn copy_embedded_dir_writes_files_to_tempdir() {
        let temp_dir = tempfile::tempdir().expect("创建临时目录应成功");
        copy_embedded_dir(&POSTGRES_MIGRATIONS, temp_dir.path()).expect("复制嵌入目录应成功");

        let core_dir = temp_dir.path().join("core");
        assert!(core_dir.exists(), "core 子目录必须被创建");

        let entries: Vec<_> = std::fs::read_dir(&core_dir)
            .expect("读取 core 目录应成功")
            .collect();
        assert_eq!(entries.len(), 16, "core 目录必须包含 16 个 SQL 文件"); // 验证文件内容非空(写入的是真实 SQL,不是空字节)
        for entry in entries {
            let entry = entry.expect("读取目录项应成功");
            let path = entry.path();
            let content = std::fs::read_to_string(&path)
                .unwrap_or_else(|e| panic!("读取 {} 应成功: {e}", path.display()));
            assert!(
                !content.trim().is_empty(),
                "文件 {} 内容不应为空",
                path.display()
            );
        }
    }

    /// copy_embedded_dir 幂等:重复写入同一目录成功且 core 仍为 16 个文件(覆盖写入)。
    #[test]
    fn copy_embedded_dir_is_idempotent() {
        let temp_dir = tempfile::tempdir().expect("创建临时目录应成功");
        copy_embedded_dir(&POSTGRES_MIGRATIONS, temp_dir.path()).expect("第一次复制应成功");
        copy_embedded_dir(&POSTGRES_MIGRATIONS, temp_dir.path()).expect("第二次复制应成功");

        let core_dir = temp_dir.path().join("core");
        let count = std::fs::read_dir(&core_dir)
            .expect("读取 core 目录应成功")
            .count();
        assert_eq!(count, 16, "重复写入后仍应为 16 个文件");
    }

    // 集成测试(需要 postgres DATABASE_URL,用 #[ignore] 标记)

    /// Scenario: run_embedded_postgres 在真实 postgres 上执行迁移。
    /// WHEN GarrisonMigration::run_embedded_postgres()(无论库此前是否已迁移)
    /// THEN dbnexus_migrations 恰好记录全部 16 个迁移(终态不变式),且本次调用无错误返回。
    #[tokio::test]
    #[serial_test::serial]
    #[ignore = "requires postgres DATABASE_URL (set SINNAN_TEST_DATABASE_URL to run)"]
    async fn run_embedded_postgres_creates_tables() {
        use dbnexus::sea_orm::{ConnectionTrait, DbBackend, Statement};

        let db_url = std::env::var("DATABASE_URL")
            .or_else(|_| std::env::var("SINNAN_TEST_DATABASE_URL"))
            .expect("DATABASE_URL 或 SINNAN_TEST_DATABASE_URL 必须设置才能运行此测试");
        let pool = init_dbnexus(&db_url)
            .await
            .expect("init_dbnexus 应成功(数据库可达)");
        let migration = GarrisonMigration::new(pool.clone());
        migration
            .run_embedded_postgres()
            .await
            .expect("run_embedded_postgres 应成功");

        // 终态不变式(竞态安全):迁移器幂等,库里已应用时本次返回 0 属正常,
        // 有效性质是「运行后全部 16 个迁移均已记录」。不设 count > 0 增量断言——        // 与 dbnexus_user_repository_works_with_postgres_backend 并发触同一库时
        // 本测试可能不是首个应用者。
        let session = pool.get_session("admin").await.expect("获取 session 失败");
        let conn = session.connection().expect("获取 connection 失败");
        let stmt = Statement::from_sql_and_values(
            DbBackend::Postgres,
            "SELECT count(*) AS cnt FROM dbnexus_migrations",
            vec![],
        );
        let row = conn
            .query_one_raw(stmt)
            .await
            .expect("查询迁移记录应成功")
            .expect("应有一行计数");
        let applied: i64 = row.try_get::<i64>("", "cnt").expect("cnt 列应存在");
        assert_eq!(applied, 16, "运行后应记录全部 16 个迁移,实际: {applied}");
    }
}