sea_orm_rocket/
pool.rs

1use rocket::figment::Figment;
2
3/// Generic [`Database`](crate::Database) driver connection pool trait.
4///
5/// This trait provides a generic interface to various database pooling
6/// implementations in the Rust ecosystem. It can be implemented by anyone.
7///
8/// This is adapted from the original `rocket_db_pools`. But on top we require
9/// `Connection` itself to be `Sync`. Hence, instead of cloning or allocating
10/// a new connection per request, here we only borrow a reference to the pool.
11///
12/// In SeaORM, only *when* you are about to execute a SQL statement will a
13/// connection be acquired from the pool, and returned as soon as the query finishes.
14/// This helps a bit with concurrency if the lifecycle of a request is long enough.
15/// ```
16#[rocket::async_trait]
17pub trait Pool: Sized + Send + Sync + 'static {
18    /// The connection type managed by this pool.
19    type Connection;
20
21    /// The error type returned by [`Self::init()`].
22    type Error: std::error::Error;
23
24    /// Constructs a pool from a [Value](rocket::figment::value::Value).
25    ///
26    /// It is up to each implementor of `Pool` to define its accepted
27    /// configuration value(s) via the `Config` associated type.  Most
28    /// integrations provided in `sea_orm_rocket` use [`Config`], which
29    /// accepts a (required) `url` and an (optional) `pool_size`.
30    ///
31    /// ## Errors
32    ///
33    /// This method returns an error if the configuration is not compatible, or
34    /// if creating a pool failed due to an unavailable database server,
35    /// insufficient resources, or another database-specific error.
36    async fn init(figment: &Figment) -> Result<Self, Self::Error>;
37
38    /// Borrows a reference to the pool
39    fn borrow(&self) -> &Self::Connection;
40}
41
42#[derive(Debug)]
43/// A mock object which impl `Pool`, for testing only
44pub struct MockPool;
45
46#[derive(Debug)]
47pub struct MockPoolErr;
48
49impl std::fmt::Display for MockPoolErr {
50    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
51        write!(f, "{self:?}")
52    }
53}
54
55impl std::error::Error for MockPoolErr {}
56
57#[rocket::async_trait]
58impl Pool for MockPool {
59    type Error = MockPoolErr;
60
61    type Connection = bool;
62
63    async fn init(_figment: &Figment) -> Result<Self, Self::Error> {
64        Ok(MockPool)
65    }
66
67    fn borrow(&self) -> &Self::Connection {
68        &true
69    }
70}