use crate::error::QuickDbError;
use crate::types::*;
use rat_logger::info;
use std::path::PathBuf;
#[derive(Debug)]
pub struct DatabaseConfigBuilder {
db_type: Option<DatabaseType>,
connection: Option<ConnectionConfig>,
pool: Option<PoolConfig>,
alias: Option<String>,
cache: Option<CacheConfig>,
id_strategy: Option<IdStrategy>,
}
impl DatabaseConfig {
pub fn builder() -> DatabaseConfigBuilder {
DatabaseConfigBuilder::new()
}
}
impl DatabaseConfigBuilder {
pub fn new() -> Self {
Self {
db_type: None,
connection: None,
pool: None,
alias: None,
cache: None,
id_strategy: None,
}
}
pub fn db_type(mut self, db_type: DatabaseType) -> Self {
self.db_type = Some(db_type);
self
}
pub fn connection(mut self, connection: ConnectionConfig) -> Self {
self.connection = Some(connection);
self
}
pub fn pool(mut self, pool: PoolConfig) -> Self {
self.pool = Some(pool);
self
}
pub fn alias<S: Into<String>>(mut self, alias: S) -> Self {
self.alias = Some(alias.into());
self
}
pub fn id_strategy(mut self, id_strategy: IdStrategy) -> Self {
self.id_strategy = Some(id_strategy);
self
}
pub fn cache(mut self, cache: CacheConfig) -> Self {
self.cache = Some(cache);
self
}
pub fn disable_cache(mut self) -> Self {
let cache_config = CacheConfig {
enabled: false, strategy: CacheStrategy::Lru,
ttl_config: TtlConfig {
default_ttl_secs: 300,
max_ttl_secs: 3600,
check_interval_secs: 60,
},
l1_config: L1CacheConfig {
max_capacity: 100,
max_memory_mb: 16,
enable_stats: false,
},
l2_config: None,
compression_config: CompressionConfig {
enabled: false,
algorithm: CompressionAlgorithm::Lz4,
threshold_bytes: 1024,
},
version: "v1".to_string(),
};
self.cache = Some(cache_config);
self
}
pub fn build(self) -> Result<DatabaseConfig, QuickDbError> {
let db_type = self
.db_type
.ok_or_else(|| crate::quick_error!(config, "数据库类型必须设置"))?;
let connection = self
.connection
.ok_or_else(|| crate::quick_error!(config, "连接配置必须设置"))?;
let pool = self
.pool
.ok_or_else(|| crate::quick_error!(config, "连接池配置必须设置"))?;
let alias = self
.alias
.ok_or_else(|| crate::quick_error!(config, "数据库别名必须设置"))?;
let id_strategy = self
.id_strategy
.ok_or_else(|| crate::quick_error!(config, "ID生成策略必须设置"))?;
Self::validate_config(&db_type, &connection)?;
info!("创建数据库配置: 别名={}, 类型={:?}", alias, db_type);
Ok(DatabaseConfig {
db_type,
connection,
pool,
alias,
cache: self.cache,
id_strategy,
})
}
fn validate_config(
db_type: &DatabaseType,
connection: &ConnectionConfig,
) -> Result<(), QuickDbError> {
match (db_type, connection) {
(DatabaseType::SQLite, ConnectionConfig::SQLite { .. }) => Ok(()),
(DatabaseType::PostgreSQL, ConnectionConfig::PostgreSQL { .. }) => Ok(()),
(DatabaseType::MySQL, ConnectionConfig::MySQL { .. }) => Ok(()),
(DatabaseType::MongoDB, ConnectionConfig::MongoDB { .. }) => Ok(()),
_ => Err(crate::quick_error!(
config,
format!("数据库类型 {:?} 与连接配置不匹配", db_type)
)),
}
}
}
impl Default for DatabaseConfigBuilder {
fn default() -> Self {
Self::new()
}
}