use std::fmt;
use std::sync::Arc;
use rustauth_core::error::RustAuthError;
use tokio::sync::RwLock;
use tokio_postgres::{Client, NoTls};
#[derive(Clone)]
pub struct TokioPostgresConnection {
pub(crate) client: Arc<Client>,
pub(crate) tx_gate: Arc<RwLock<()>>,
}
impl fmt::Debug for TokioPostgresConnection {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("TokioPostgresConnection")
.finish_non_exhaustive()
}
}
impl TokioPostgresConnection {
pub fn from_client(client: Client) -> Self {
Self {
client: Arc::new(client),
tx_gate: Arc::new(RwLock::new(())),
}
}
pub async fn connect(database_url: &str) -> Result<Self, RustAuthError> {
let (client, connection) = tokio_postgres::connect(database_url, NoTls)
.await
.map_err(crate::errors::postgres_error)?;
tokio::spawn(async move {
let _connection_result = connection.await;
});
Ok(Self::from_client(client))
}
#[doc(hidden)]
pub fn duplicate_client_unshared_gate(connection: &Self) -> Self {
Self {
client: Arc::clone(&connection.client),
tx_gate: Arc::new(RwLock::new(())),
}
}
}