use anyhow::{Result, anyhow};
use std::path::PathBuf;
pub struct DbConfig {
db_url: String,
profile: Option<String>,
}
impl DbConfig {
pub fn load(profile: Option<&str>) -> Result<Self> {
load_env();
let (db_url, profile) = resolve_db_url(profile)?;
Ok(Self { db_url, profile })
}
pub fn from_env_var(profile_var: &str) -> Result<Self> {
let profile = profile_from_env(profile_var);
Self::load(profile.as_deref())
}
pub fn from_url(url: impl Into<String>) -> Self {
Self {
db_url: url.into(),
profile: None,
}
}
pub fn postgres_connection_string(&self) -> &str {
&self.db_url
}
pub fn profile_name(&self) -> Option<&str> {
self.profile.as_deref()
}
}
pub fn env_file() -> Option<PathBuf> {
let mut dir = std::env::current_dir().ok()?;
loop {
let path = dir.join(".env");
if path.is_file() {
return Some(path);
}
dir = dir.parent()?.to_path_buf();
}
}
pub fn load_env() -> Option<PathBuf> {
let path = env_file();
match &path {
Some(path) => {
let _ = dotenvy::from_path(path);
}
None => {
let _ = dotenvy::dotenv();
}
}
path
}
pub fn profile_from_env(var: &str) -> Option<String> {
std::env::var(var)
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
}
fn profile_key(name: &str) -> String {
format!("DB_URL_{}", name.to_uppercase().replace('-', "_"))
}
fn resolve_db_url(profile: Option<&str>) -> Result<(String, Option<String>)> {
if let Some(name) = profile {
let key = profile_key(name);
return match std::env::var(&key) {
Ok(url) if !url.trim().is_empty() => Ok((url, Some(name.to_string()))),
_ => Err(anyhow!(
"profile {name:?} needs {key} in the environment. \
A profile is a name for a database: set {key} to its connection string, \
or drop --profile to use DB_URL."
)),
};
}
match std::env::var("DB_URL") {
Ok(url) if !url.trim().is_empty() => Ok((url, None)),
_ => Err(anyhow!(
"DB_URL is not set. It is the whole connection string, e.g. \
postgresql://user:password@host:5432/database?sslmode=require — \
which is what your provider gives you."
)),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_url_needs_nothing_from_the_environment() {
let url = "postgresql://user:pw@example.invalid:5432/thing?sslmode=require";
let config = DbConfig::from_url(url);
assert_eq!(config.postgres_connection_string(), url);
assert_eq!(config.profile_name(), None);
}
#[test]
fn from_url_accepts_anything_that_becomes_a_string() {
assert_eq!(
DbConfig::from_url(String::from("postgres://a/b")).postgres_connection_string(),
"postgres://a/b"
);
}
#[test]
fn a_profile_name_is_a_variable_name() {
assert_eq!(profile_key("staging"), "DB_URL_STAGING");
assert_eq!(profile_key("my-test"), "DB_URL_MY_TEST");
assert_eq!(profile_key("Dev"), "DB_URL_DEV");
}
}