Skip to main content

rocket_db_pools/
database.rs

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