use std::path::PathBuf;
use crate::{CreatePoolError, Manager, Pool, PoolBuilder, PoolConfig, Runtime};
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Config {
pub path: PathBuf,
#[cfg_attr(feature = "serde", serde(skip_serializing))]
pub passphrase: Vec<u8>,
pub pool: Option<PoolConfig>,
}
impl Config {
#[must_use]
pub fn new(path: impl Into<PathBuf>, passphrase: &[u8]) -> Self {
Self {
path: path.into(),
passphrase: passphrase.to_vec(),
pool: None,
}
}
pub fn create_pool(&self, runtime: Runtime) -> Result<Pool, CreatePoolError> {
self.builder(runtime)
.map_err(CreatePoolError::Config)?
.build()
.map_err(CreatePoolError::Build)
}
pub fn builder(&self, runtime: Runtime) -> Result<PoolBuilder, ConfigError> {
let manager = Manager::from_config(self, runtime);
Ok(Pool::builder(manager)
.config(self.get_pool_config())
.runtime(runtime))
}
#[must_use]
pub fn get_pool_config(&self) -> PoolConfig {
self.pool.unwrap_or_default()
}
pub(crate) fn create_database(&self) -> Result<citadel::Database, ConfigError> {
if self.path.as_os_str().is_empty() {
citadel::DatabaseBuilder::new("")
.passphrase(&self.passphrase)
.create_in_memory()
} else if self.path.exists() {
citadel::DatabaseBuilder::new(&self.path)
.passphrase(&self.passphrase)
.open()
} else {
citadel::DatabaseBuilder::new(&self.path)
.passphrase(&self.passphrase)
.create()
}
}
}
pub type ConfigError = citadel::Error;