Lines
100 %
Functions
75 %
Branches
use super::DBError;
use std::sync::OnceLock;
/// The admin database URL: set explicitly once, otherwise read from
/// `DATABASE_URL` on first use. The first resolution is final.
pub(super) struct UrlSource {
resolved: OnceLock<Option<String>>,
}
impl UrlSource {
pub(super) const fn new() -> Self {
Self {
resolved: OnceLock::new(),
pub(super) fn set(&self, url: String) -> Result<(), DBError> {
self.resolved
.set(Some(url))
.map_err(|_| DBError::UrlAlreadyResolved)
pub(super) fn get_or_env(&self, env: impl FnOnce() -> Option<String>) -> Option<&str> {
self.resolved.get_or_init(env).as_deref()
static DB_URL: UrlSource = UrlSource::new();
fn env_url() -> Option<String> {
std::env::var("DATABASE_URL").ok()
/// Makes `url` the admin database URL instead of `DATABASE_URL`.
///
/// # Errors
/// [`DBError::UrlAlreadyResolved`] if a URL was already set or any code
/// already resolved the URL from the environment.
pub fn use_url(url: String) -> Result<(), DBError> {
DB_URL.set(url)
/// The admin database URL the server was configured with.
/// [`DBError::MissingUrl`] if no URL was set and `DATABASE_URL` is unset.
pub fn admin_database_url() -> Result<String, DBError> {
current_url().map(str::to_owned).ok_or(DBError::MissingUrl)
pub(super) fn current_url() -> Option<&'static str> {
DB_URL.get_or_env(env_url)
#[cfg(test)]
mod tests {
use super::*;
fn env(url: &'static str) -> impl FnOnce() -> Option<String> {
move || Some(url.to_owned())
#[test]
fn explicit_url_wins_over_env() {
let source = UrlSource::new();
assert!(source.set("postgres://explicit/db".into()).is_ok());
assert_eq!(
source.get_or_env(env("postgres://env/db")),
Some("postgres://explicit/db")
);
fn env_is_used_when_nothing_was_set() {
Some("postgres://env/db")
fn missing_everywhere_resolves_to_none() {
assert_eq!(source.get_or_env(|| None), None);
fn second_set_is_refused() {
assert!(source.set("postgres://a/db".into()).is_ok());
assert!(matches!(
source.set("postgres://b/db".into()),
Err(DBError::UrlAlreadyResolved)
));
assert_eq!(source.get_or_env(|| None), Some("postgres://a/db"));
fn set_after_first_use_is_refused() {
source.set("postgres://late/db".into()),