use valence_core::error::{Error, Result};
pub const URL_ENV: &str = "DATABASE_URL";
#[derive(Debug, Clone, Default)]
pub struct PostgresBackendBuilder {
url: Option<String>,
}
impl PostgresBackendBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn from_env_defaults(mut self) -> Self {
if self.url.is_none() {
self.url = postgres_url_from_env();
}
self
}
pub fn url(mut self, url: impl Into<String>) -> Self {
self.url = Some(url.into());
self
}
pub fn has_url(&self) -> bool {
self.url.is_some() || postgres_url_from_env().is_some()
}
pub fn resolve(self) -> Result<String> {
let builder = self.from_env_defaults();
builder
.url
.ok_or_else(|| Error::Internal(format!("{URL_ENV} not set for postgres adapter")))
}
pub async fn build(self) -> Result<super::backend::PostgresBackend> {
let url = self.resolve()?;
super::backend::PostgresBackend::connect(&url).await
}
}
fn postgres_url_from_env() -> Option<String> {
std::env::var(URL_ENV)
.ok()
.map(|v| v.trim().to_string())
.filter(|v| !v.is_empty())
}