riback_db_client 0.1.1

Riback db client
Documentation
use tokio_postgres::{types::ToSql, Client, Config, NoTls, Row, ToStatement};

type Result<T> = core::result::Result<T, Error>;

#[derive(Debug)]
pub enum Error {
    PostgresError(tokio_postgres::Error),
}

impl From<tokio_postgres::Error> for Error {
    fn from(value: tokio_postgres::Error) -> Self {
        Error::PostgresError(value)
    }
}

pub struct RibackDbClient {
    client: Client,
}

impl RibackDbClient {
    pub async fn new<T>(
        user: impl Into<String>,
        password: T,
        dbname: impl Into<String>,
        host: impl Into<String>,
        port: u16,
    ) -> Result<Self>
    where
        T: AsRef<[u8]>,
    {
        let mut config = Config::new();
        config.user(user).password(password).dbname(dbname).host(host).port(port);

        let (client, connection) = config.connect(NoTls).await?;

        tokio::spawn(async move {
            if let Err(e) = connection.await {
                eprintln!("connection error: {}", e);
            }
        });

        Ok(RibackDbClient { client })
    }

    pub async fn query<T>(
        &self,
        statement: &T,
        params: &[&(dyn ToSql + Sync)],
    ) -> Result<Vec<Row>>
    where
        T: ?Sized + ToStatement,
    {
        Ok(self.client.query(statement, params).await?)
    }
}