use crate::error::{GarrisonError, GarrisonResult};
use dbnexus::DbPool;
use std::path::{Path, PathBuf};
pub async fn init_dbnexus(url: &str) -> GarrisonResult<DbPool> {
DbPool::new(url)
.await
.map_err(|e| GarrisonError::Dao(format!("dao-dbnexus-init::{}", 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)
}
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(all(test, feature = "db-sqlite"))]
mod tests {
use super::*;
use 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_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",
];
for expected in &expected_tables {
assert!(
table_names.contains(&expected.to_string()),
"核心表 {} 应存在于 sqlite_master,实际表: {:?}",
expected,
table_names
);
}
assert_eq!(
expected_tables.len(),
10,
"应有 10 张核心表(8 核心 + app_user_ext + app_user_device)"
);
}
#[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, 10, "应有 10 张 app_ 前缀的表");
}
#[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");
}
}