feat(config): App can take environ variables

- Change log level of SQLx to TRACE
This commit is contained in:
minhtrannhat 2024-05-11 22:30:21 -04:00
parent 96a6b6a351
commit d96eae1fec
Signed by: minhtrannhat
GPG Key ID: E13CFA85C53F8062
7 changed files with 57 additions and 27 deletions

12
Cargo.lock generated
View File

@ -618,6 +618,7 @@ dependencies = [
"reqwest",
"secrecy",
"serde",
"serde-aux",
"sqlx",
"tokio",
"tracing",
@ -1987,6 +1988,17 @@ dependencies = [
"serde_derive",
]
[[package]]
name = "serde-aux"
version = "4.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d2e8bfba469d06512e11e3311d4d051a4a387a5b42d010404fecf3200321c95"
dependencies = [
"chrono",
"serde",
"serde_json",
]
[[package]]
name = "serde_derive"
version = "1.0.197"

View File

@ -30,6 +30,7 @@ once_cell = "1.19.0"
secrecy = { version = "0.8.0", features = ["serde"] }
tracing-actix-web = "0.7.10"
h2 = "0.3.26"
serde-aux = "4.5.0"
[dependencies.sqlx]
version = "0.7"

View File

@ -1,2 +1,4 @@
application:
host: 127.0.0.1
database:
require_ssl: false

View File

@ -1,2 +1,4 @@
application:
host: 0.0.0.0
database:
require_ssl: true

View File

@ -1,4 +1,7 @@
use secrecy::{ExposeSecret, Secret};
use serde_aux::field_attributes::deserialize_number_from_string;
use sqlx::postgres::{PgConnectOptions, PgSslMode};
use sqlx::ConnectOptions;
#[derive(serde::Deserialize)]
pub struct Settings {
@ -8,6 +11,7 @@ pub struct Settings {
#[derive(serde::Deserialize)]
pub struct ApplicationSettings {
#[serde(deserialize_with = "deserialize_number_from_string")]
pub port: u16,
pub host: String,
}
@ -16,9 +20,11 @@ pub struct ApplicationSettings {
pub struct DatabaseSettings {
pub username: String,
pub password: Secret<String>,
#[serde(deserialize_with = "deserialize_number_from_string")]
pub port: u16,
pub host: String,
pub database_name: String,
pub require_ssl: bool,
}
pub fn get_configuration() -> Result<Settings, config::ConfigError> {
@ -39,6 +45,15 @@ pub fn get_configuration() -> Result<Settings, config::ConfigError> {
.add_source(config::File::from(
configuration_directory.join(environment_filename),
))
// take settings from environment variables
// with a prefix of APP and __ as separator
//
// E.g `APP_APPLICATION_PORT=5001` would set Settings.application.port
.add_source(
config::Environment::with_prefix("APP")
.prefix_separator("_")
.separator("__"),
)
.build()?;
settings.try_deserialize::<Settings>()
@ -73,24 +88,26 @@ Use either `local` or `production`.",
}
impl DatabaseSettings {
pub fn connection_string(&self) -> Secret<String> {
Secret::new(format!(
"postgres://{}:{}@{}:{}/{}",
self.username,
self.password.expose_secret(),
self.host,
self.port,
self.database_name
))
// for normal usage
pub fn with_db(&self) -> PgConnectOptions {
let mut options = self.without_db().database(&self.database_name);
options = options.log_statements(tracing_log::log::LevelFilter::Trace);
options
}
pub fn connection_string_without_db(&self) -> Secret<String> {
Secret::new(format!(
"postgres://{}:{}@{}:{}",
self.username,
self.password.expose_secret(),
self.host,
self.port
))
// for testings, we will set the database name with arbitrary values
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

@ -2,8 +2,7 @@ use std::net::TcpListener;
use email_newsletter_api::telemetry::{get_subscriber, init_subscriber};
use email_newsletter_api::{configuration::get_configuration, startup};
use secrecy::ExposeSecret;
use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
@ -16,8 +15,7 @@ async fn main() -> Result<(), std::io::Error> {
);
init_subscriber(subscriber);
let db_conn = PgPool::connect_lazy(configuration.database.connection_string().expose_secret())
.expect("Failed to connect to PostgreSQL");
let db_conn = PgPoolOptions::new().connect_lazy_with(configuration.database.with_db());
let listener = TcpListener::bind(format!(
"{}:{}",

View File

@ -3,7 +3,6 @@ use email_newsletter_api::{
telemetry::{get_subscriber, init_subscriber},
};
use once_cell::sync::Lazy;
use secrecy::ExposeSecret;
use sqlx::{Connection, Executor, PgConnection, PgPool};
use std::net::TcpListener;
use uuid::Uuid;
@ -58,17 +57,16 @@ pub async fn spawn_app() -> TestApp {
}
pub async fn configure_test_database(db_config: &DatabaseSettings) -> PgPool {
let mut connection =
PgConnection::connect(db_config.connection_string_without_db().expose_secret())
.await
.expect("Failed to connect to Postgres");
let mut connection = PgConnection::connect_with(&db_config.without_db())
.await
.expect("Failed to connect to Postgres");
connection
.execute(format!(r#"CREATE DATABASE "{}";"#, db_config.database_name).as_str())
.await
.expect("Failed to create database");
let conn_pool = PgPool::connect(db_config.connection_string().expose_secret())
let conn_pool = PgPool::connect_with(db_config.with_db())
.await
.expect("Failed to connect to PostgreSQL pool");