avantis_utils/db/
diesel.rs1use super::*;
2
3use ::diesel::pg::PgConnection;
4use ::diesel::r2d2::{ConnectionManager, Pool, PoolError, PooledConnection};
5use ::diesel::{Connection, ConnectionError};
6use thiserror::Error;
7use tracing::instrument;
8
9pub type PgPool = Pool<ConnectionManager<PgConnection>>;
10pub type PgPooledConnection = PooledConnection<ConnectionManager<PgConnection>>;
11
12pub trait DieselDatabaseConfig {
13 fn init_pool(&self) -> Result<PgPool, Error>;
14}
15
16impl DieselDatabaseConfig for DatabaseConfig {
17 #[instrument(skip_all, name = "db::diesel::init_pool", fields(host = %self.host, db = %self.db_name))]
18 fn init_pool(&self) -> Result<PgPool, Error> {
19 let database_url = self.postgres_uri();
20 PgConnection::establish(&database_url)?;
21
22 let manager = ConnectionManager::<PgConnection>::new(database_url);
23 let pool = Pool::builder()
24 .max_size(self.max_connections)
25 .connection_timeout(self.connection_timeout())
26 .build(manager)?;
27
28 Ok(pool)
29 }
30}
31
32pub fn fetch_connection(pool: &PgPool) -> Result<PgPooledConnection, Error> {
33 Ok(pool.get()?)
34}
35
36#[derive(Error, Debug)]
37pub enum Error {
38 #[error("connection error: `{0}`")]
39 ConnectionError(#[from] ConnectionError),
40 #[error("pool error: `{0}`")]
41 PoolError(#[from] PoolError),
42}