Skip to main content

rocket_db_pools/
database.rs

1use std::ops::{Deref, DerefMut};
2
3use rocket::{error, Build, Ignite, Phase, Rocket, Sentinel, Orbit};
4use rocket::fairing::{self, Fairing, Info, Kind};
5use rocket::request::{FromRequest, Outcome, Request};
6use rocket::figment::{Figment, providers::Serialized};
7use rocket::http::Status;
8
9use crate::{Pool, Config, Configurable};
10
11/// Derivable trait which ties a database [`Pool`] with a configuration name.
12///
13/// This trait should rarely, if ever, be implemented manually. Instead, it
14/// should be derived:
15///
16/// ```rust
17/// # #[cfg(feature = "deadpool_redis")] mod _inner {
18/// # use rocket::launch;
19/// use rocket_db_pools::{deadpool_redis, Database};
20///
21/// #[derive(Database)]
22/// #[database("memdb")]
23/// struct Db(deadpool_redis::Pool);
24///
25/// #[launch]
26/// fn rocket() -> _ {
27///     rocket::build().attach(Db::init())
28/// }
29/// # }
30/// ```
31///
32/// See the [`Database` derive](derive@crate::Database) for details.
33pub trait Database: From<Self::Pool> + DerefMut<Target = Self::Pool> + Send + Sync + 'static {
34    /// The [`Pool`] type of connections to this database.
35    ///
36    /// When `Database` is derived, this takes the value of the `Inner` type in
37    /// `struct Db(Inner)`.
38    type Pool: Pool;
39
40    /// The configuration name for this database.
41    ///
42    /// When `Database` is derived, this takes the value `"name"` in the
43    /// `#[database("name")]` attribute.
44    const NAME: &'static str;
45
46    /// Returns a fairing that initializes the database and its connection pool.
47    ///
48    /// # Example
49    ///
50    /// ```rust
51    /// # #[cfg(feature = "deadpool_postgres")] mod _inner {
52    /// # use rocket::launch;
53    /// use rocket_db_pools::{deadpool_postgres, Database};
54    ///
55    /// #[derive(Database)]
56    /// #[database("pg_db")]
57    /// struct Db(deadpool_postgres::Pool);
58    ///
59    /// #[launch]
60    /// fn rocket() -> _ {
61    ///     rocket::build().attach(Db::init())
62    /// }
63    /// # }
64    /// ```
65    fn init() -> Initializer<Self> {
66        Initializer::new()
67    }
68
69    /// Returns a fairing that initializes the database and its connection pool.
70    ///
71    /// Unlike [`Self::init()`], this method allows you to configure the
72    /// database driver via the function `f`. The pool must implement
73    /// [`Configurable`]. See [`Configurable::Options`] for the configuration
74    /// types used by each driver.
75    ///
76    /// The function `f` is called with a reference to the database's [`Config`]
77    /// and the driver's options after applying Rocket's configuration and
78    /// defaults. The returned options are used to create the pool, overriding
79    /// any previously configured values.
80    ///
81    /// This method does not allow the function `f` to fail. If `f` is fallible,
82    /// use [`Self::try_custom()`] instead.
83    ///
84    /// # Example
85    ///
86    /// ```rust
87    /// # #[cfg(feature = "sqlx_sqlite")] mod _inner {
88    /// use std::time::Duration;
89    /// use rocket_db_pools::{sqlx, Database};
90    ///
91    /// #[derive(Database)]
92    /// #[database("sqlite_db")]
93    /// struct Db(sqlx::SqlitePool);
94    ///
95    /// fn main() {
96    ///     rocket::build().attach(Db::custom(|_config, (pool, connection)| {
97    ///         (pool, connection.busy_timeout(Duration::from_secs(10)))
98    ///     }));
99    /// }
100    /// # }
101    /// ```
102    fn custom<F>(f: F) -> Initializer<Self>
103        where Self::Pool: Configurable,
104              F: Fn(
105                  &Config,
106                  <Self::Pool as Configurable>::Options
107              ) -> <Self::Pool as Configurable>::Options + Send + Sync + 'static
108    {
109        Self::try_custom(move |config, options| Ok(f(config, options)))
110    }
111
112    /// Returns a fairing that initializes the database and its connection pool.
113    ///
114    /// This variant of [`Self::custom()`] allows a fallible `f`. The error type
115    /// is the pool's [`Pool::Error`]. If `f` returns an error during
116    /// initialization, it will cancel the launch.
117    fn try_custom<F>(f: F) -> Initializer<Self>
118        where Self::Pool: Configurable,
119              F: Fn(
120                  &Config,
121                  <Self::Pool as Configurable>::Options
122              ) -> Result<<Self::Pool as Configurable>::Options, <Self::Pool as Pool>::Error>
123                  + Send + Sync + 'static
124    {
125        let mut initializer = Self::init();
126        initializer.1 = Some(Box::new(f));
127        initializer
128    }
129
130    /// Returns a reference to the initialized database in `rocket`. The
131    /// initializer fairing returned by `init()` must have already executed for
132    /// `Option` to be `Some`. This is guaranteed to be the case if the fairing
133    /// is attached and either:
134    ///
135    ///   * Rocket is in the [`Orbit`](rocket::Orbit) phase. That is, the
136    ///     application is running. This is always the case in request guards
137    ///     and liftoff fairings,
138    ///   * _or_ Rocket is in the [`Build`](rocket::Build) or
139    ///     [`Ignite`](rocket::Ignite) phase and the `Initializer` fairing has
140    ///     already been run. This is the case in all fairing callbacks
141    ///     corresponding to fairings attached _after_ the `Initializer`
142    ///     fairing.
143    ///
144    /// # Example
145    ///
146    /// Run database migrations in an ignite fairing. It is imperative that the
147    /// migration fairing be registered _after_ the `init()` fairing.
148    ///
149    /// ```rust
150    /// # #[cfg(feature = "sqlx_sqlite")] mod _inner {
151    /// # use rocket::launch;
152    /// use rocket::{Rocket, Build};
153    /// use rocket::fairing::{self, AdHoc};
154    ///
155    /// use rocket_db_pools::{sqlx, Database};
156    ///
157    /// #[derive(Database)]
158    /// #[database("sqlite_db")]
159    /// struct Db(sqlx::SqlitePool);
160    ///
161    /// async fn run_migrations(rocket: Rocket<Build>) -> fairing::Result {
162    ///     if let Some(db) = Db::fetch(&rocket) {
163    ///         // run migrations using `db`. get the inner type with &db.0.
164    ///         Ok(rocket)
165    ///     } else {
166    ///         Err(rocket)
167    ///     }
168    /// }
169    ///
170    /// #[launch]
171    /// fn rocket() -> _ {
172    ///     rocket::build()
173    ///         .attach(Db::init())
174    ///         .attach(AdHoc::try_on_ignite("DB Migrations", run_migrations))
175    /// }
176    /// # }
177    /// ```
178    fn fetch<P: Phase>(rocket: &Rocket<P>) -> Option<&Self> {
179        if let Some(db) = rocket.state() {
180            return Some(db);
181        }
182
183        let conn = std::any::type_name::<Self>();
184        error!("`{conn}::init()` is not attached\n\
185            the fairing must be attached to use `{conn}` in routes.");
186
187        None
188    }
189}
190
191/// A [`Fairing`] which initializes a [`Database`] and its connection pool.
192///
193/// A value of this type can be created for any type `D` that implements
194/// [`Database`] via [`Database::init()`], [`Database::custom()`], or
195/// [`Database::try_custom()`]. Normally, a value of this type _never_ needs to
196/// be constructed directly. This documentation exists purely as a reference.
197///
198/// This fairing initializes a database pool. Specifically, it:
199///
200///   1. Reads the configuration at `databases.db_name`, where `db_name` is
201///      [`Database::NAME`].
202///
203///   2. Sets [`Config`](crate::Config) defaults on the configuration figment.
204///
205///   3. Calls [`Pool::init()`] or, when customized,
206///      [`Configurable::init_with()`].
207///
208///   4. Stores the database instance in managed storage, retrievable via
209///      [`Database::fetch()`].
210///
211/// The name of the fairing itself is `Initializer<D>`, with `D` replaced with
212/// the type name `D` unless a name is explicitly provided via
213/// [`Self::with_name()`].
214pub struct Initializer<D: Database>(Option<&'static str>, Option<Box<dyn Initialize<D::Pool>>>);
215
216/// A request guard which retrieves a single connection to a [`Database`].
217///
218/// For a database type of `Db`, a request guard of `Connection<Db>` retrieves a
219/// single connection to `Db`.
220///
221/// The request guard succeeds if the database was initialized by the
222/// [`Initializer`] fairing and a connection is available within
223/// [`connect_timeout`](crate::Config::connect_timeout) seconds.
224///   * If the `Initializer` fairing was _not_ attached, the guard _fails_ with
225///   status `InternalServerError`. A [`Sentinel`] guards this condition, and so
226///   this type of error is unlikely to occur. A `None` error is returned.
227///   * If a connection is not available within `connect_timeout` seconds or
228///   another error occurs, the guard _fails_ with status `ServiceUnavailable`
229///   and the error is returned in `Some`.
230///
231/// ## Deref
232///
233/// A type of `Connection<Db>` dereferences, mutably and immutably, to the
234/// native database connection type. The [driver table](crate#supported-drivers)
235/// lists the concrete native `Deref` types.
236///
237/// # Example
238///
239/// ```rust
240/// # #[cfg(feature = "sqlx_sqlite")] mod _inner {
241/// # use rocket::get;
242/// # type Pool = rocket_db_pools::sqlx::SqlitePool;
243/// use rocket_db_pools::{Database, Connection};
244///
245/// #[derive(Database)]
246/// #[database("db")]
247/// struct Db(Pool);
248///
249/// #[get("/")]
250/// async fn db_op(db: Connection<Db>) {
251///     // use `&*db` to get an immutable borrow to the native connection type
252///     // use `&mut *db` to get a mutable borrow to the native connection type
253/// }
254/// # }
255/// ```
256pub struct Connection<D: Database>(<D::Pool as Pool>::Connection);
257
258impl<D: Database> Initializer<D> {
259    /// Returns a database initializer fairing for `D`.
260    ///
261    /// This method should never need to be called manually. See the [crate
262    /// docs](crate) for usage information.
263    pub fn new() -> Self {
264        Self(None, None)
265    }
266
267    /// Returns a database initializer fairing for `D` with name `name`.
268    ///
269    /// This method should never need to be called manually. See the [crate
270    /// docs](crate) for usage information.
271    pub fn with_name(name: &'static str) -> Self {
272        Self(Some(name), None)
273    }
274}
275
276impl<D: Database> Connection<D> {
277    /// Returns the internal connection value. See the [`Connection` Deref
278    /// column](crate#supported-drivers) for the expected type of this value.
279    ///
280    /// Note that `Connection<D>` derefs to the internal connection type, so
281    /// using this method is likely unnecessary. See [deref](Connection#deref)
282    /// for examples.
283    ///
284    /// # Example
285    ///
286    /// ```rust
287    /// # #[cfg(feature = "sqlx_sqlite")] mod _inner {
288    /// # use rocket::get;
289    /// # type Pool = rocket_db_pools::sqlx::SqlitePool;
290    /// use rocket_db_pools::{Database, Connection};
291    ///
292    /// #[derive(Database)]
293    /// #[database("db")]
294    /// struct Db(Pool);
295    ///
296    /// #[get("/")]
297    /// async fn db_op(db: Connection<Db>) {
298    ///     let inner = db.into_inner();
299    /// }
300    /// # }
301    /// ```
302    pub fn into_inner(self) -> <D::Pool as Pool>::Connection {
303        self.0
304    }
305}
306
307#[rocket::async_trait]
308trait Initialize<P: Pool>: Send + Sync {
309    async fn init(&self, figment: &Figment) -> Result<P, P::Error>;
310}
311
312#[rocket::async_trait]
313impl<P, F> Initialize<P> for F
314    where P: Configurable,
315          F: Fn(&Config, P::Options) -> Result<P::Options, P::Error> + Send + Sync
316{
317    async fn init(&self, figment: &Figment) -> Result<P, P::Error> {
318        P::init_with(figment, self).await
319    }
320}
321
322#[rocket::async_trait]
323impl<D: Database> Fairing for Initializer<D> {
324    fn info(&self) -> Info {
325        Info {
326            name: self.0.unwrap_or(std::any::type_name::<Self>()),
327            kind: Kind::Ignite | Kind::Shutdown,
328        }
329    }
330
331    async fn on_ignite(&self, rocket: Rocket<Build>) -> fairing::Result {
332        let workers: usize = rocket.figment()
333            .extract_inner(rocket::Config::WORKERS)
334            .unwrap_or_else(|_| rocket::Config::default().workers);
335
336        let figment = rocket.figment()
337            .focus(&format!("databases.{}", D::NAME))
338            .join(Serialized::default("max_connections", workers * 4))
339            .join(Serialized::default("connect_timeout", 5));
340
341        let result = match &self.1 {
342            Some(init) => init.init(&figment).await,
343            None => <D::Pool>::init(&figment).await,
344        };
345
346        match result {
347            Ok(pool) => Ok(rocket.manage(D::from(pool))),
348            Err(e) => {
349                error!("database initialization failed: {e}");
350                Err(rocket)
351            }
352        }
353    }
354
355    async fn on_shutdown(&self, rocket: &Rocket<Orbit>) {
356        if let Some(db) = D::fetch(rocket) {
357            db.close().await;
358        }
359    }
360}
361
362#[rocket::async_trait]
363impl<'r, D: Database> FromRequest<'r> for Connection<D> {
364    type Error = Option<<D::Pool as Pool>::Error>;
365
366    async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
367        match D::fetch(req.rocket()) {
368            Some(db) => match db.get().await {
369                Ok(conn) => Outcome::Success(Connection(conn)),
370                Err(e) => Outcome::Error((Status::ServiceUnavailable, Some(e))),
371            },
372            None => Outcome::Error((Status::InternalServerError, None)),
373        }
374    }
375}
376
377impl<D: Database> Sentinel for Connection<D> {
378    fn abort(rocket: &Rocket<Ignite>) -> bool {
379        D::fetch(rocket).is_none()
380    }
381}
382
383impl<D: Database> Deref for Connection<D> {
384    type Target = <D::Pool as Pool>::Connection;
385
386    fn deref(&self) -> &Self::Target {
387        &self.0
388    }
389}
390
391impl<D: Database> DerefMut for Connection<D> {
392    fn deref_mut(&mut self) -> &mut Self::Target {
393        &mut self.0
394    }
395}