Files
crank/crates/crank-registry/src/postgres/connection.rs
T

71 lines
2.2 KiB
Rust

use std::time::Duration;
use sqlx::{
AssertSqlSafe, PgPool,
postgres::{PgConnectOptions, PgPoolOptions},
};
use crate::{MigrationAuthority, error::RegistryError};
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?;
MigrationAuthority::require_current(&pool).await?;
Ok(Self { pool })
}
pub fn pool(&self) -> &PgPool {
&self.pool
}
pub async fn ping(&self) -> Result<(), RegistryError> {
sqlx::query("select 1").execute(&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(AssertSqlSafe(format!("set search_path to {schema}")))
.execute(&pool)
.await?;
}
let registry = Self { pool };
MigrationAuthority::require_current(&registry.pool).await?;
Ok(registry)
}
}