use std::sync::Arc;
use pg_wired::protocol::types::RawRow;
use pg_wired::{AsyncConn, AsyncPool};
use crate::encode::SqlParam;
use crate::error::TypedError;
use crate::row::Row;
#[derive(Debug)]
pub struct SharedPool {
pool: Arc<AsyncPool>,
}
impl SharedPool {
pub async fn connect(
addr: &str,
user: &str,
password: &str,
database: &str,
size: usize,
) -> Result<Self, pg_wired::PgWireError> {
let pool = AsyncPool::connect(addr, user, password, database, size).await?;
Ok(Self { pool })
}
pub async fn get(&self) -> SharedClient {
let conn = self.pool.get_async().await;
SharedClient { conn }
}
pub fn size(&self) -> usize {
self.pool.size()
}
pub async fn alive_count(&self) -> usize {
self.pool.alive_count().await
}
pub async fn close(&self) -> Result<(), pg_wired::PgWireError> {
self.pool.close().await
}
pub async fn exec_transaction(
&self,
setup_sql: &str,
query_sql: &str,
params: &[Option<&[u8]>],
param_oids: &[u32],
) -> Result<Vec<RawRow>, TypedError> {
self.pool
.exec_transaction(setup_sql, query_sql, params, param_oids)
.await
.map_err(|e| TypedError::from(e).with_sql(query_sql))
}
pub async fn exec_query(
&self,
sql: &str,
params: &[Option<&[u8]>],
param_oids: &[u32],
) -> Result<Vec<RawRow>, TypedError> {
self.pool
.exec_query(sql, params, param_oids)
.await
.map_err(|e| TypedError::from(e).with_sql(sql))
}
}
#[derive(Debug, Clone)]
pub struct SharedClient {
conn: Arc<AsyncConn>,
}
impl SharedClient {
pub fn conn(&self) -> &AsyncConn {
&self.conn
}
pub async fn query(&self, sql: &str, params: &[&dyn SqlParam]) -> Result<Vec<Row>, TypedError> {
crate::query::Client::query_on_conn(&self.conn, sql, params).await
}
pub async fn execute(&self, sql: &str, params: &[&dyn SqlParam]) -> Result<u64, TypedError> {
crate::query::Client::execute_on_conn(&self.conn, sql, params).await
}
pub async fn simple_query(&self, sql: &str) -> Result<(), TypedError> {
crate::query::Client::simple_query_on_conn(&self.conn, sql).await
}
pub fn is_alive(&self) -> bool {
self.conn.is_alive()
}
}