refactor: extract DB init to database.rs
This commit is contained in:
36
k-tv-backend/api/src/database.rs
Normal file
36
k-tv-backend/api/src/database.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration as StdDuration;
|
||||
|
||||
use crate::config::Config;
|
||||
use infra::run_migrations;
|
||||
use k_core::db::DatabasePool;
|
||||
|
||||
pub async fn init_database(config: &Config) -> anyhow::Result<Arc<DatabasePool>> {
|
||||
tracing::info!("Connecting to database: {}", config.database_url);
|
||||
|
||||
#[cfg(all(feature = "sqlite", not(feature = "postgres")))]
|
||||
let db_type = k_core::db::DbType::Sqlite;
|
||||
|
||||
#[cfg(all(feature = "postgres", not(feature = "sqlite")))]
|
||||
let db_type = k_core::db::DbType::Postgres;
|
||||
|
||||
// Both features enabled: fall back to URL inspection at runtime
|
||||
#[cfg(all(feature = "sqlite", feature = "postgres"))]
|
||||
let db_type = if config.database_url.starts_with("postgres") {
|
||||
k_core::db::DbType::Postgres
|
||||
} else {
|
||||
k_core::db::DbType::Sqlite
|
||||
};
|
||||
|
||||
let db_config = k_core::db::DatabaseConfig {
|
||||
db_type,
|
||||
url: config.database_url.clone(),
|
||||
max_connections: config.db_max_connections,
|
||||
min_connections: config.db_min_connections,
|
||||
acquire_timeout: StdDuration::from_secs(30),
|
||||
};
|
||||
|
||||
let pool = k_core::db::connect(&db_config).await?;
|
||||
run_migrations(&pool).await?;
|
||||
Ok(Arc::new(pool))
|
||||
}
|
||||
Reference in New Issue
Block a user