Environment variables at runtime to connect to database

This commit is contained in:
Alphonse Paix
2025-08-22 16:01:20 +02:00
parent 80b8029844
commit 19ddc8958d
5 changed files with 62 additions and 27 deletions

View File

@@ -1,5 +1,7 @@
use secrecy::{ExposeSecret, SecretString};
use serde::Deserialize;
use serde_aux::field_attributes::deserialize_number_from_string;
use sqlx::postgres::{PgConnectOptions, PgSslMode};
pub fn get_configuration() -> Result<Settings, config::ConfigError> {
let base_path = std::env::current_dir().expect("Failed to determine the current directory");
@@ -13,6 +15,11 @@ pub fn get_configuration() -> Result<Settings, config::ConfigError> {
let settings = config::Config::builder()
.add_source(config::File::from(config_dir.join("base.yaml")))
.add_source(config::File::from(config_dir.join(environment_filename)))
.add_source(
config::Environment::with_prefix("APP")
.prefix_separator("_")
.prefix("__"),
)
.build()?;
settings.try_deserialize::<Settings>()
@@ -55,6 +62,7 @@ pub struct Settings {
#[derive(Deserialize)]
pub struct ApplicationSettings {
#[serde(deserialize_with = "deserialize_number_from_string")]
pub port: u16,
pub host: String,
}
@@ -63,32 +71,29 @@ pub struct ApplicationSettings {
pub struct DatabaseSettings {
pub username: String,
pub password: SecretString,
#[serde(deserialize_with = "deserialize_number_from_string")]
pub port: u16,
pub host: String,
pub database_name: String,
pub require_ssl: bool,
}
impl DatabaseSettings {
pub fn connection_string(&self) -> SecretString {
format!(
"postgres://{}:{}@{}:{}/{}",
self.username,
self.password.expose_secret(),
self.host,
self.port,
self.database_name
)
.into()
pub fn with_db(&self) -> PgConnectOptions {
self.without_db().database(&self.database_name)
}
pub fn connection_string_without_db(&self) -> SecretString {
format!(
"postgres://{}:{}@{}:{}",
self.username,
self.password.expose_secret(),
self.host,
self.port
)
.into()
pub fn without_db(&self) -> PgConnectOptions {
let ssl_mode = if self.require_ssl {
PgSslMode::Require
} else {
PgSslMode::Prefer
};
PgConnectOptions::new()
.host(&self.host)
.username(&self.username)
.password(self.password.expose_secret())
.port(self.port)
.ssl_mode(ssl_mode)
}
}