feat: add ssh for database access

This commit is contained in:
Sandro Eiler 2024-02-07 21:59:28 +01:00
parent 1d5b9699b9
commit 13162f6470
5 changed files with 29 additions and 26 deletions

View file

@ -1,5 +1,8 @@
use secrecy::{ExposeSecret, Secret};
use serde_aux::field_attributes::deserialize_number_from_string;
use sqlx::postgres::PgConnectOptions;
use sqlx::postgres::PgSslMode;
use sqlx::ConnectOptions;
#[derive(serde::Deserialize)]
/// The setting collection.
@ -102,24 +105,24 @@ pub fn get_configuration() -> Result<Settings, config::ConfigError> {
}
impl DatabaseSettings {
pub fn connection_string(&self) -> Secret<String> {
Secret::new(format!(
"postgres://{}:{}@{}:{}/{}",
self.username,
self.password.expose_secret(),
self.host,
self.port,
self.name
))
pub fn without_db(&self) -> PgConnectOptions {
let ssl_mode = if self.require_ssl {
PgSslMode::Require
} else {
// Try an encrypted connection, fallback to unencrypted if it fails
PgSslMode::Prefer
};
PgConnectOptions::new()
.host(&self.host)
.username(&self.username)
.password(self.password.expose_secret())
.port(self.port)
.ssl_mode(ssl_mode)
}
pub fn connection_string_without_db(&self) -> Secret<String> {
Secret::new(format!(
"postgres://{}:{}@{}:{}",
self.username,
self.password.expose_secret(),
self.host,
self.port
))
pub fn with_db(&self) -> PgConnectOptions {
let mut options = self.without_db().database(&self.name);
options = options.log_statements(tracing::log::LevelFilter::Trace);
options
}
}

View file

@ -1,7 +1,6 @@
use learn_axum::configuration::get_configuration;
use learn_axum::startup;
use learn_axum::telemetry::{get_subscriber, init_subscriber};
use secrecy::ExposeSecret;
use sqlx::postgres::PgPoolOptions;
use tokio::net::TcpListener;
@ -20,7 +19,6 @@ async fn main() {
let listener = TcpListener::bind(addr).await.unwrap(); //.expect("Unable to bind to port");
let connection_pool = PgPoolOptions::new()
.acquire_timeout(std::time::Duration::from_secs(2))
.connect_lazy(configuration.database.connection_string().expose_secret())
.expect("Failed to connect to Postgres.");
.connect_lazy_with(configuration.database.with_db());
startup::run(listener, connection_pool).await.unwrap();
}