Skip to main content

valence_backend_postgres/
config.rs

1//! Postgres connection configuration and builder.
2
3use valence_core::error::{Error, Result};
4
5/// Environment variable for Postgres connection URL.
6pub const URL_ENV: &str = "DATABASE_URL";
7
8/// Builder for [`super::backend::PostgresBackend`].
9#[derive(Debug, Clone, Default)]
10pub struct PostgresBackendBuilder {
11    url: Option<String>,
12}
13
14impl PostgresBackendBuilder {
15    /// Empty builder; set fields or call [`Self::from_env_defaults`].
16    pub fn new() -> Self {
17        Self::default()
18    }
19
20    /// Fill unset URL from `DATABASE_URL`.
21    pub fn from_env_defaults(mut self) -> Self {
22        if self.url.is_none() {
23            self.url = postgres_url_from_env();
24        }
25        self
26    }
27
28    /// Postgres connection URL.
29    pub fn url(mut self, url: impl Into<String>) -> Self {
30        self.url = Some(url.into());
31        self
32    }
33
34    /// Whether a URL is set explicitly or resolvable via env defaults.
35    pub fn has_url(&self) -> bool {
36        self.url.is_some() || postgres_url_from_env().is_some()
37    }
38
39    /// Resolve URL without connecting.
40    pub fn resolve(self) -> Result<String> {
41        let builder = self.from_env_defaults();
42        builder
43            .url
44            .ok_or_else(|| Error::Internal(format!("{URL_ENV} not set for postgres adapter")))
45    }
46
47    /// Connect and return a [`super::backend::PostgresBackend`].
48    pub async fn build(self) -> Result<super::backend::PostgresBackend> {
49        let url = self.resolve()?;
50        super::backend::PostgresBackend::connect(&url).await
51    }
52}
53
54fn postgres_url_from_env() -> Option<String> {
55    std::env::var(URL_ENV)
56        .ok()
57        .map(|v| v.trim().to_string())
58        .filter(|v| !v.is_empty())
59}