distributed_lock_postgres/
connection.rs

1//! Connection pool management for PostgreSQL locks.
2
3use distributed_lock_core::error::{LockError, LockResult};
4use sqlx::PgPool;
5
6/// PostgreSQL connection source.
7#[derive(Debug, Clone)]
8pub enum PostgresConnection {
9    /// Connection string - library manages pooling.
10    ConnectionString(String),
11    /// External connection pool.
12    Pool(PgPool),
13}
14
15impl PostgresConnection {
16    /// Creates a connection pool from a connection string.
17    pub async fn create_pool(connection_string: &str) -> LockResult<PgPool> {
18        sqlx::PgPool::connect(connection_string).await.map_err(|e| {
19            LockError::Connection(Box::new(std::io::Error::other(format!(
20                "failed to create connection pool: {e}"
21            ))))
22        })
23    }
24
25    /// Gets or creates a connection pool.
26    pub async fn get_pool(&self) -> LockResult<PgPool> {
27        match self {
28            Self::ConnectionString(conn_str) => Self::create_pool(conn_str).await,
29            Self::Pool(pool) => Ok(pool.clone()),
30        }
31    }
32}
33
34/// Configuration for PostgreSQL distributed locks.
35#[derive(Debug, Clone)]
36pub struct PostgresLockConfig {
37    /// Connection source.
38    pub connection: PostgresConnection,
39    /// Whether to use transaction-scoped locks.
40    pub use_transaction: bool,
41    /// Keepalive cadence for long-held locks.
42    pub keepalive_cadence: Option<std::time::Duration>,
43}
44
45impl PostgresLockConfig {
46    /// Creates a new configuration.
47    pub fn new(connection: PostgresConnection) -> Self {
48        Self {
49            connection,
50            use_transaction: false,
51            keepalive_cadence: None,
52        }
53    }
54}