From 93170f4cb1b15283d50f4ed4d6c2c19f8cad9745 Mon Sep 17 00:00:00 2001 From: fluo10 Date: Tue, 27 May 2025 17:49:52 +0900 Subject: [PATCH] Update database initialization --- Cargo.toml | 2 +- lazy-supplements-migration/src/lib.rs | 2 +- lazy-supplements/Cargo.toml | 9 ++- lazy-supplements/src/cli/mod.rs | 2 + lazy-supplements/src/entity/node.rs | 2 +- .../src/entity/record_deletion.rs | 4 +- lazy-supplements/src/global/database.rs | 59 ++++++++++++------- lazy-supplements/src/global/mod.rs | 3 + lazy-supplements/src/lib.rs | 2 +- 9 files changed, 55 insertions(+), 30 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 0d6f0d4..c1f333a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = [ "examples/timestamper", "lazy-supplements", "lazy-supplements-*" ] +members = [ "examples/*", "lazy-supplements", "lazy-supplements-*" ] [workspace.package] edition = "2024" diff --git a/lazy-supplements-migration/src/lib.rs b/lazy-supplements-migration/src/lib.rs index 3794aba..13606f6 100644 --- a/lazy-supplements-migration/src/lib.rs +++ b/lazy-supplements-migration/src/lib.rs @@ -1,6 +1,6 @@ use sea_orm_migration::{prelude::*, schema::*}; -mod m20220101_000001_create_lazy_supplements_tables; +pub mod m20220101_000001_create_lazy_supplements_tables; pub struct Migrator; diff --git a/lazy-supplements/Cargo.toml b/lazy-supplements/Cargo.toml index 42b2e63..2826cbc 100644 --- a/lazy-supplements/Cargo.toml +++ b/lazy-supplements/Cargo.toml @@ -6,6 +6,10 @@ description.workspace = true license.workspace = true repository.workspace = true +[features] +default = [] +test = ["dep:tempfile"] + [dependencies] base64 = "0.22.1" chrono = "0.4.41" @@ -13,9 +17,8 @@ chrono-tz = "0.10.3" clap = { version = "4.5.38", features = ["derive"] } libp2p.workspace = true sea-orm = { version = "1.1.11", features = ["sqlx-sqlite", "runtime-tokio-native-tls", "macros", "with-chrono", "with-uuid"] } -sea-orm-migration.workspace = true serde = { version = "1.0.219", features = ["derive"] } -tempfile = "3.20.0" +tempfile = { version = "3.20.0", optional = true } thiserror = "2.0.12" tokio = { version = "1.45.0", features = ["macros", "rt"] } toml = "0.8.22" @@ -23,3 +26,5 @@ uuid = { version = "1.17.0", features = ["v4"] } [dev-dependencies] lazy-supplements-migration.workspace = true +sea-orm-migration.workspace = true +tempfile = "3.20.0" \ No newline at end of file diff --git a/lazy-supplements/src/cli/mod.rs b/lazy-supplements/src/cli/mod.rs index 715937c..856c57c 100644 --- a/lazy-supplements/src/cli/mod.rs +++ b/lazy-supplements/src/cli/mod.rs @@ -4,6 +4,8 @@ mod connect; mod init; mod server; +pub use server::ServerArgs; + pub fn default_config_path() -> PathBuf { todo!() } \ No newline at end of file diff --git a/lazy-supplements/src/entity/node.rs b/lazy-supplements/src/entity/node.rs index 78a6723..464b46b 100644 --- a/lazy-supplements/src/entity/node.rs +++ b/lazy-supplements/src/entity/node.rs @@ -49,7 +49,7 @@ mod tests { #[tokio::test] async fn check_insert_node() { - let db = GLOBAL.get_or_init_temporary_database().await; + let db = crate::global::get_or_init_temporary_database().await; ActiveModel{ peer_id: Set(identity::Keypair::generate_ed25519().public().to_peer_id().to_string()), diff --git a/lazy-supplements/src/entity/record_deletion.rs b/lazy-supplements/src/entity/record_deletion.rs index ff0f6f2..c739dd2 100644 --- a/lazy-supplements/src/entity/record_deletion.rs +++ b/lazy-supplements/src/entity/record_deletion.rs @@ -38,11 +38,11 @@ mod tests { use super::*; use uuid::Uuid; - use crate::global::GLOBAL; + use crate::global::get_or_init_temporary_database; #[tokio::test] async fn check_insert_record_deletion() { - let db = GLOBAL.get_or_init_temporary_database().await; + let db = get_or_init_temporary_database().await; assert!(ActiveModel{ table_name: Set("test_table".to_string()), diff --git a/lazy-supplements/src/global/database.rs b/lazy-supplements/src/global/database.rs index c6863d8..a8c0ad3 100644 --- a/lazy-supplements/src/global/database.rs +++ b/lazy-supplements/src/global/database.rs @@ -1,55 +1,70 @@ -use sea_orm::{ConnectOptions, Database, DatabaseConnection}; -use sea_orm_migration::MigratorTrait; +use std::path::Path; + +use sea_orm::{ConnectOptions, Database, DbErr, DatabaseConnection}; use crate::error::Error; use tokio::sync::OnceCell; use super::Global; +#[cfg(any(test, feature="test"))] +pub static TEST_DATABASE_URL: std::sync::LazyLock = std::sync::LazyLock::new(|| { + let mut temp_path = tempfile::NamedTempFile::new().unwrap().into_temp_path(); + temp_path.disable_cleanup(true); + println!("{}", temp_path.as_os_str().to_str().unwrap()); + temp_path +}); + impl Global { fn get_database(&self) -> Option<&DatabaseConnection> { self.database.get() } - async fn get_or_try_init_database(&self, options: T, _: U) -> Result<&DatabaseConnection, Error> + async fn get_or_try_init_database(&self, path: T, migration: F) -> Result<&DatabaseConnection, Error> where - T: Into, - U: MigratorTrait, + T: AsRef, + F: FnOnce(DatabaseConnection) -> Fut, + Fut: Future> { + let url = "sqlite://".to_string() + path.as_ref().to_str().unwrap() + "?mode=rwc"; + Ok(self.database.get_or_try_init(|| async { - let db = Database::connect(options).await?; - U::up(&db, None).await?; - Ok::(db) + let db = Database::connect(&url).await?; + Ok::(migration(db).await?) }).await?) } + #[cfg(any(test, feature="test"))] + pub async fn get_or_try_init_temporary_database(&self, migration: F) -> Result<&DatabaseConnection, Error> + where + F: FnOnce(DatabaseConnection) -> Fut, + Fut: Future> + { + self.get_or_try_init_database(&*TEST_DATABASE_URL, migration).await + } } + + + #[cfg(test)] pub mod tests { use std::sync::LazyLock; use lazy_supplements_migration::Migrator; + use sea_orm_migration::MigratorTrait; use crate::global::GLOBAL; use super::*; - pub static TEST_DATABASE_URL: LazyLock = LazyLock::new(|| { - let mut temp_path = tempfile::NamedTempFile::new().unwrap().into_temp_path(); - temp_path.disable_cleanup(true); - let url = "sqlite://".to_string() + temp_path.as_os_str().to_str().unwrap() + "?mode=rwc"; - println!("{}", &url); - url - }); - - impl Global { - pub async fn get_or_init_temporary_database(&self) -> &DatabaseConnection { - - self.get_or_try_init_database(&*TEST_DATABASE_URL, Migrator).await.unwrap() - } + pub async fn get_or_init_temporary_database() -> &'static DatabaseConnection { + GLOBAL.get_or_try_init_temporary_database( |x| async { + Migrator::up(&x, None).await?; + Ok(x) + }).await.unwrap() } #[tokio::test] async fn connect_database () { - let db = GLOBAL.get_or_init_temporary_database().await; + let db = get_or_init_temporary_database().await; assert!(db.ping().await.is_ok()); } diff --git a/lazy-supplements/src/global/mod.rs b/lazy-supplements/src/global/mod.rs index ba53e22..0de3e9d 100644 --- a/lazy-supplements/src/global/mod.rs +++ b/lazy-supplements/src/global/mod.rs @@ -12,3 +12,6 @@ pub struct Global { server_config: OnceCell, database: OnceCell, } + +#[cfg(any(test, feature="test"))] +pub use database::tests::get_or_init_temporary_database; \ No newline at end of file diff --git a/lazy-supplements/src/lib.rs b/lazy-supplements/src/lib.rs index 40013b6..2f64b69 100644 --- a/lazy-supplements/src/lib.rs +++ b/lazy-supplements/src/lib.rs @@ -2,4 +2,4 @@ pub mod cli; pub mod config; pub mod entity; pub mod error; -pub mod global; \ No newline at end of file +pub mod global;