Environment variables at runtime to connect to database

This commit is contained in:
Alphonse Paix
2025-08-22 16:01:20 +02:00
parent 1567f94b1f
commit a7473bb7f5
7 changed files with 66 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)
}
}

View File

@@ -1,5 +1,4 @@
use secrecy::ExposeSecret;
use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
use tokio::net::TcpListener;
use zero2prod::{configuration::get_configuration, startup::run, telemetry::init_subscriber};
@@ -14,8 +13,7 @@ async fn main() {
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
let connection_pool =
PgPool::connect_lazy(configuration.database.connection_string().expose_secret()).unwrap();
let connection_pool = PgPoolOptions::new().connect_lazy_with(configuration.database.with_db());
run(listener, connection_pool).await
}