db_pool/sync/
conn_pool.rs

1use std::{ops::Deref, sync::Arc};
2
3use r2d2::Pool;
4use uuid::Uuid;
5
6use super::backend::{r#trait::Backend, Error as BackendError};
7
8struct ConnectionPool<B: Backend> {
9    backend: Arc<B>,
10    db_id: Uuid,
11    conn_pool: Option<Pool<B::ConnectionManager>>,
12    is_restricted: bool,
13}
14
15impl<B: Backend> Deref for ConnectionPool<B> {
16    type Target = Pool<B::ConnectionManager>;
17
18    fn deref(&self) -> &Self::Target {
19        self.conn_pool
20            .as_ref()
21            .expect("conn_pool must always contain a [Some] value")
22    }
23}
24
25impl<B: Backend> Drop for ConnectionPool<B> {
26    fn drop(&mut self) {
27        self.conn_pool = None;
28        (*self.backend).drop(self.db_id, self.is_restricted).ok();
29    }
30}
31
32/// Reusable connection pool wrapper
33pub struct ReusableConnectionPool<B: Backend>(ConnectionPool<B>);
34
35impl<B: Backend> ReusableConnectionPool<B> {
36    pub(crate) fn new(
37        backend: Arc<B>,
38    ) -> Result<Self, BackendError<B::ConnectionError, B::QueryError>> {
39        let db_id = Uuid::new_v4();
40        let conn_pool = backend.create(db_id, true)?;
41
42        Ok(Self(ConnectionPool {
43            backend,
44            db_id,
45            conn_pool: Some(conn_pool),
46            is_restricted: true,
47        }))
48    }
49
50    pub(crate) fn clean(&mut self) -> Result<(), BackendError<B::ConnectionError, B::QueryError>> {
51        self.0.backend.clean(self.0.db_id)
52    }
53}
54
55impl<B: Backend> Deref for ReusableConnectionPool<B> {
56    type Target = Pool<B::ConnectionManager>;
57
58    fn deref(&self) -> &Self::Target {
59        &self.0
60    }
61}
62
63/// Single-use connection pool wrapper
64pub struct SingleUseConnectionPool<B: Backend>(ConnectionPool<B>);
65
66impl<B: Backend> SingleUseConnectionPool<B> {
67    pub(crate) fn new(
68        backend: Arc<B>,
69    ) -> Result<Self, BackendError<B::ConnectionError, B::QueryError>> {
70        let db_id = Uuid::new_v4();
71        let conn_pool = backend.create(db_id, false)?;
72
73        Ok(Self(ConnectionPool {
74            backend,
75            db_id,
76            conn_pool: Some(conn_pool),
77            is_restricted: false,
78        }))
79    }
80}
81
82impl<B: Backend> Deref for SingleUseConnectionPool<B> {
83    type Target = Pool<B::ConnectionManager>;
84
85    fn deref(&self) -> &Self::Target {
86        &self.0
87    }
88}