Refine Rust architecture boundaries
This commit is contained in:
1 parent
a31862aeeb
commit
7df9b48513
18 files changed
+1376
-1052
No files matched your search
@@ -0,0 +1,70 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use sqlx::{
|
||||
PgPool,
|
||||
postgres::{PgConnectOptions, PgPoolOptions},
|
||||
};
|
||||
|
||||
use crate::{error::RegistryError, migrations};
|
||||
|
||||
use super::{PostgresPoolConfig, PostgresRegistry};
|
||||
|
||||
impl PostgresRegistry {
|
||||
pub async fn connect(database_url: &str) -> Result<Self, RegistryError> {
|
||||
Self::connect_in_schema(database_url, None).await
|
||||
}
|
||||
|
||||
pub async fn connect_with_options(
|
||||
connect_options: PgConnectOptions,
|
||||
) -> Result<Self, RegistryError> {
|
||||
Self::connect_with_options_and_pool_config(connect_options, PostgresPoolConfig::default())
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn connect_with_options_and_pool_config(
|
||||
connect_options: PgConnectOptions,
|
||||
pool_config: PostgresPoolConfig,
|
||||
) -> Result<Self, RegistryError> {
|
||||
let pool = PgPoolOptions::new()
|
||||
.max_connections(pool_config.max_connections)
|
||||
.min_connections(pool_config.min_connections)
|
||||
.acquire_timeout(Duration::from_millis(pool_config.acquire_timeout_ms))
|
||||
.idle_timeout(Duration::from_millis(pool_config.idle_timeout_ms))
|
||||
.max_lifetime(Duration::from_millis(pool_config.max_lifetime_ms))
|
||||
.connect_with(connect_options)
|
||||
.await?;
|
||||
migrations::apply_postgres(&pool).await?;
|
||||
Ok(Self { pool })
|
||||
}
|
||||
|
||||
pub fn pool(&self) -> &PgPool {
|
||||
&self.pool
|
||||
}
|
||||
|
||||
pub async fn migrate(&self) -> Result<(), RegistryError> {
|
||||
migrations::apply_postgres(&self.pool).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn connect_in_schema(
|
||||
database_url: &str,
|
||||
schema: Option<&str>,
|
||||
) -> Result<Self, RegistryError> {
|
||||
let pool = PgPoolOptions::new()
|
||||
.min_connections(0)
|
||||
.max_connections(1)
|
||||
.idle_timeout(std::time::Duration::from_secs(1))
|
||||
.connect(database_url)
|
||||
.await?;
|
||||
|
||||
if let Some(schema) = schema {
|
||||
sqlx::query(&format!("set search_path to {schema}"))
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
}
|
||||
|
||||
let registry = Self { pool };
|
||||
registry.migrate().await?;
|
||||
Ok(registry)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user