use distributed_lock_core::error::{LockError, LockResult};
use sqlx::PgPool;
#[derive(Debug, Clone)]
pub enum PostgresConnection {
ConnectionString(String),
Pool(PgPool),
}
impl PostgresConnection {
pub async fn create_pool(connection_string: &str) -> LockResult<PgPool> {
sqlx::PgPool::connect(connection_string).await.map_err(|e| {
LockError::Connection(Box::new(std::io::Error::other(format!(
"failed to create connection pool: {e}"
))))
})
}
pub async fn get_pool(&self) -> LockResult<PgPool> {
match self {
Self::ConnectionString(conn_str) => Self::create_pool(conn_str).await,
Self::Pool(pool) => Ok(pool.clone()),
}
}
}
#[derive(Debug, Clone)]
pub struct PostgresLockConfig {
pub connection: PostgresConnection,
pub use_transaction: bool,
pub keepalive_cadence: Option<std::time::Duration>,
}
impl PostgresLockConfig {
pub fn new(connection: PostgresConnection) -> Self {
Self {
connection,
use_transaction: false,
keepalive_cadence: None,
}
}
}