use crate::error::{GarrisonError, GarrisonResult};
use dbnexus::DbPool;
use std::path::{Path, PathBuf};
#[cfg(feature = "embedded-migrations")]
static POSTGRES_MIGRATIONS: include_dir::Dir<'_> = include_dir::include_dir!("migrations/postgres");
pub async fn init_dbnexus(url: &str) -> GarrisonResult<DbPool> {
DbPool::new(url)
.await
.map_err(|e| GarrisonError::Dao(format!("dao-dbnexus-init::{}", e)))
}
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)))
}
pub struct GarrisonMigration {
pool: DbPool,
base_dir: PathBuf,
}
impl GarrisonMigration {
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 }
}
pub fn pool(&self) -> &DbPool {
&self.pool
}
pub async fn migrate_core(&self) -> GarrisonResult<u32> {
self.run_dir(&self.base_dir.join("core")).await
}
pub async fn migrate_extensions(&self) -> GarrisonResult<u32> {
self.run_dir(&self.base_dir.join("extensions")).await
}
pub async fn migrate_tenant(&self) -> GarrisonResult<u32> {
self.run_dir(&self.base_dir.join("tenant")).await
}
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)
}
#[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}")))?;
copy_embedded_dir(&POSTGRES_MIGRATIONS, temp_dir.path())
.map_err(|e| GarrisonError::Dao(format!("embedded-migrations-write::{e}")))?;
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)
}
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))
})
}
}
#[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) => {
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};
#[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()
);
}
#[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), "池应真实可用");
}
#[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(|_| ())
);
}
#[tokio::test]
async fn migrate_core_empty_dir_returns_zero() {
let pool = init_dbnexus("sqlite::memory:").await.unwrap();
let tmp = tempfile::tempdir().unwrap();
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);
}
#[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 个迁移文件");
}
#[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();
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();
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();
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 个迁移文件");
}
#[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"));
}
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")
}
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")
}
#[tokio::test]
async fn dbnexus_crud_full_cycle() {
let pool = init_dbnexus("sqlite::memory:").await.unwrap();
let session = pool.get_session("admin").await.unwrap();
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 后表应为空");
}
#[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, "回滚后表应为空");
}
#[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 条记录");
}
#[tokio::test]
async fn migrate_core_creates_all_core_tables() {
let pool = init_dbnexus("sqlite::memory:").await.unwrap();
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 应成功");
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();
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)"
);
}
#[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);
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)"
);
}
#[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");
}
}
#[cfg(all(test, feature = "embedded-migrations"))]
mod embedded_migrations_tests {
use super::*;
#[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:?}"
);
}
#[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 文件"); 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()
);
}
}
#[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 个文件");
}
#[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 应成功");
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}");
}
}