Skip to main content

rocket_db_pools/
lib.rs

1//! Asynchronous database driver connection pooling integration for Rocket.
2//!
3//! # Quickstart
4//!
5//! 1. Add `rocket_db_pools` as a dependency with one or more [database driver
6//!    features](#supported-drivers) enabled:
7//!
8//!    ```toml
9//!    [dependencies.rocket_db_pools]
10//!    version = "0.3.0"
11//!    features = ["sqlx_sqlite"]
12//!    ```
13//!
14//! 2. Choose a name for your database, here `sqlite_logs`.
15//!    [Configure](#configuration) _at least_ a URL for the database:
16//!
17//!    ```toml
18//!    [default.databases.sqlite_logs]
19//!    url = "/path/to/database.sqlite"
20//!    ```
21//!
22//! 3. [Derive](derive@Database) [`Database`] for a unit type (`Logs` here)
23//!    which wraps the selected driver's [`Pool`] type (see [the driver
24//!    table](#supported-drivers)) and is decorated with `#[database("name")]`.
25//!    Attach `Type::init()` to your application's `Rocket` to initialize the
26//!    database pool:
27//!
28//!    ```rust
29//!    # #[cfg(feature = "sqlx_sqlite")] mod _inner {
30//!    # use rocket::launch;
31//!    use rocket_db_pools::{sqlx, Database};
32//!
33//!    #[derive(Database)]
34//!    #[database("sqlite_logs")]
35//!    struct Logs(sqlx::SqlitePool);
36//!
37//!    #[launch]
38//!    fn rocket() -> _ {
39//!        rocket::build().attach(Logs::init())
40//!    }
41//!    # }
42//!    ```
43//!
44//! 4. Use [`Connection<Type>`](Connection) as a request guard to retrieve an
45//!    active database connection, which dereferences to the native type in the
46//!    [`Connection` deref](#supported-drivers) column.
47//!
48//!    ```rust
49//!    # #[cfg(feature = "sqlx_sqlite")] mod _inner {
50//!    # use rocket::{get, response::Responder};
51//!    # use rocket_db_pools::{sqlx, Database};
52//!    # #[derive(Database)]
53//!    # #[database("sqlite_logs")]
54//!    # struct Logs(sqlx::SqlitePool);
55//!    #
56//!    # #[derive(Responder)]
57//!    # struct Log(String);
58//!    #
59//!    use rocket_db_pools::Connection;
60//!    use rocket_db_pools::sqlx::Row;
61//!
62//!    #[get("/<id>")]
63//!    async fn read(mut db: Connection<Logs>, id: i64) -> Option<Log> {
64//!        sqlx::query("SELECT content FROM logs WHERE id = ?").bind(id)
65//!            .fetch_one(&mut **db).await
66//!            .and_then(|r| Ok(Log(r.try_get(0)?)))
67//!            .ok()
68//!    }
69//!    # }
70//!    ```
71//!
72//!    Alternatively, use a reference to the database type as a request guard to
73//!    retrieve the entire pool, but note that unlike retrieving a `Connection`,
74//!    doing so does _not_ guarantee that a connection is available:
75//!
76//!    ```rust
77//!    # #[cfg(feature = "sqlx_sqlite")] mod _inner {
78//!    # use rocket::{get, response::Responder};
79//!    # use rocket_db_pools::{sqlx, Database};
80//!    # #[derive(Database)]
81//!    # #[database("sqlite_logs")]
82//!    # struct Logs(sqlx::SqlitePool);
83//!    #
84//!    # #[derive(Responder)]
85//!    # struct Log(String);
86//!    #
87//!    use rocket_db_pools::sqlx::Row;
88//!
89//!    #[get("/<id>")]
90//!    async fn read(db: &Logs, id: i64) -> Option<Log> {
91//!        sqlx::query("SELECT content FROM logs WHERE id = ?").bind(id)
92//!            .fetch_one(&db.0).await
93//!            .and_then(|r| Ok(Log(r.try_get(0)?)))
94//!            .ok()
95//!    }
96//!    # }
97//!    ```
98//!
99//! # Supported Drivers
100//!
101//! At present, this crate supports _four_ drivers: [`deadpool`], [`sqlx`],
102//! [`mongodb`], and [`diesel`]. Each driver may support multiple databases.
103//! Drivers have a varying degree of support for graceful shutdown, affected by
104//! the `Type::init()` fairing on Rocket shutdown.
105//!
106//! ## `deadpool` (v0.13)
107//!
108//! | Database | Feature                     | [`Pool`] Type               | [`Connection`] Deref                 |
109//! |----------|-----------------------------|-----------------------------|--------------------------------------|
110//! | Postgres | `deadpool_postgres` (v0.14) | [`deadpool_postgres::Pool`] | [`deadpool_postgres::ClientWrapper`] |
111//! | Redis    | `deadpool_redis` (v0.23)    | [`deadpool_redis::Pool`]    | [`deadpool_redis::Connection`]       |
112//!
113//! On shutdown, new connections are denied. Shutdown _does not_ wait for
114//! connections to be returned.
115//!
116//! ## `sqlx` (v0.9)
117//!
118//! | Database | Feature         | [`Pool`] Type        | [`Connection`] Deref                     |
119//! |----------|-----------------|----------------------|------------------------------------------|
120//! | Postgres | `sqlx_postgres` | [`sqlx::PgPool`]     | [`sqlx::pool::PoolConnection<Postgres>`] |
121//! | MySQL    | `sqlx_mysql`    | [`sqlx::MySqlPool`]  | [`sqlx::pool::PoolConnection<MySql>`]    |
122//! | SQLite   | `sqlx_sqlite`   | [`sqlx::SqlitePool`] | [`sqlx::pool::PoolConnection<Sqlite>`]   |
123//!
124//! [`sqlx::PgPool`]: https://docs.rs/sqlx/0.9/sqlx/type.PgPool.html
125//! [`sqlx::MySqlPool`]: https://docs.rs/sqlx/0.9/sqlx/type.MySqlPool.html
126//! [`sqlx::SqlitePool`]: https://docs.rs/sqlx/0.9/sqlx/type.SqlitePool.html
127//! [`sqlx::pool::PoolConnection<Postgres>`]:
128//! https://docs.rs/sqlx/0.9/sqlx/pool/struct.PoolConnection.html
129//! [`sqlx::pool::PoolConnection<MySql>`]:
130//! https://docs.rs/sqlx/0.9/sqlx/pool/struct.PoolConnection.html
131//! [`sqlx::pool::PoolConnection<Sqlite>`]:
132//! https://docs.rs/sqlx/0.9/sqlx/pool/struct.PoolConnection.html
133//!
134//! On shutdown, new connections are denied. Shutdown waits for connections to
135//! be returned.
136//!
137//! ## `mongodb` (v3)
138//!
139//! | Database | Feature   | [`Pool`] Type and [`Connection`] Deref |
140//! |----------|-----------|----------------------------------------|
141//! | MongoDB  | `mongodb` | [`mongodb::Client`]                    |
142//!
143//! Graceful shutdown is not supported.
144//!
145//! ## `diesel` (v2)
146//!
147//! | Database | Feature           | [`Pool`] Type         | [`Connection`] Deref             |
148//! |----------|-------------------|-----------------------|----------------------------------|
149//! | Postgres | `diesel_postgres` | [`diesel::PgPool`]    | [`diesel::AsyncPgConnection`]    |
150//! | MySQL    | `diesel_mysql`    | [`diesel::MysqlPool`] | [`diesel::AsyncMysqlConnection`] |
151//!
152//! See [`diesel`] for usage details.
153//!
154//! On shutdown, new connections are denied. Shutdown _does not_ wait for
155//! connections to be returned.
156//!
157//! ## Enabling Additional Driver Features
158//!
159//! Only the minimal features for each driver crate are enabled by
160//! `rocket_db_pools`. To use additional driver functionality exposed via its
161//! crate's features, you'll need to depend on the crate directly with those
162//! features enabled in `Cargo.toml`:
163//!
164//! ```toml
165//! [dependencies.sqlx]
166//! version = "0.9.0"
167//! default-features = false
168//! features = ["macros", "migrate"]
169//!
170//! [dependencies.rocket_db_pools]
171//! version = "0.3.0"
172//! features = ["sqlx_sqlite"]
173//! ```
174//!
175//! TLS connections are supported by `deadpool_postgres` and `diesel_postgres`
176//! when the `postgres_rustls_native_certs` feature is enabled:
177//!
178//! ```toml
179//! [dependencies.rocket_db_pools]
180//! version = "0.3.0"
181//! features = ["diesel_postgres", "postgres_rustls_native_certs"]
182//! ```
183//!
184//! To require TLS, set `sslmode=require` in the database URL. With
185//! `sslmode=prefer`, a connection without TLS is allowed if the server does not
186//! support TLS. The server's certificate and hostname are verified using the
187//! platform's native root certificates.
188//!
189//! To trust a private CA, set `SSL_CERT_FILE` to a PEM certificate bundle or
190//! `SSL_CERT_DIR` to a directory of PEM certificates. These replace the native
191//! roots. Errors loading certificates are logged. If no root certificates can
192//! be loaded, TLS connections fail.
193//!
194//! **Note:** Without this feature, `deadpool_postgres` and `diesel_postgres`
195//! connect without TLS. The `sqlx_postgres` driver supports TLS without
196//! additional features.
197//!
198//! # Configuration
199//!
200//! Configuration for a database named `db_name` is deserialized from a
201//! `databases.db_name` configuration parameter into a [`Config`] structure via
202//! Rocket's [configuration facilities](rocket::config). By default,
203//! configuration can be provided in `Rocket.toml`:
204//!
205//! ```toml
206//! [default.databases.db_name]
207//! url = "db.sqlite"
208//!
209//! # Only `url` is required. These have sane defaults and are optional.
210//! min_connections = 64
211//! max_connections = 1024
212//! connect_timeout = 5
213//! idle_timeout = 120
214//! ```
215//!
216//! Or via environment variables:
217//!
218//! ```sh
219//! ROCKET_DATABASES='{db_name={url="db.sqlite",idle_timeout=120}}'
220//! ```
221//!
222//! See [`Config`] for details on configuration parameters.
223//!
224//! **Note:** `deadpool` and `diesel` drivers do not support and thus ignore the
225//! `min_connections` value. For these drivers, `idle_timeout` limits the time
226//! allowed to recycle a connection before reuse, including any health check.
227//! It does not close idle connections. By default, no timeout is set.
228//!
229//! ## Redis
230//!
231//! The `deadpool_redis` driver accepts an additional `response_timeout` option:
232//!
233//! ```toml
234//! [default.databases.redis]
235//! url = "redis://localhost:6379"
236//! response_timeout = 0.5
237//! ```
238//!
239//! This option limits how long the client waits for a command's response, in
240//! seconds, and defaults to `0.5`. Both integer and fractional values are
241//! accepted. Set `response_timeout = 0` to disable the timeout, for example,
242//! when using blocking commands such as `BLPOP`. A timeout does not cancel a
243//! command already executing on Redis. Negative, nonfinite, out-of-range, and
244//! nonnumeric values result in an [`Error::Config`] during initialization.
245//! Other drivers ignore this option.
246//!
247//! The Redis driver's connection timeout is disabled. Instead, Deadpool limits
248//! both the time spent waiting for a pooled connection and the time spent
249//! creating a connection to [`Config::connect_timeout`] seconds each. These
250//! limits apply separately. Redis health checks also use `response_timeout`,
251//! even when `idle_timeout` is unset.
252//!
253//! ## Driver Defaults
254//!
255//! Some drivers provide configuration defaults different from the underlying
256//! database's defaults. A best-effort attempt is made to document those
257//! differences below:
258//!
259//! * `deadpool_redis`
260//!
261//!   - response timeout   : `0.5` seconds
262//!   - connection timeout : disabled (Deadpool's creation timeout applies)
263//!
264//! * `sqlx_sqlite`
265//!
266//!   - foreign keys   : `enabled`
267//!   - journal mode   : `WAL`
268//!   - create-missing :  `enabled`
269//!   - synchronous    : `full` (even when `WAL`)
270//!   - busy timeout   : `connect_timeout`
271//!
272//! * `sqlx_postgres`
273//!
274//!   - sslmode                  : `prefer`
275//!   - statement-cache-capacity : `100`
276//!   - user                     : result of `whoami`
277//!
278//! * `sqlx_mysql`
279//!
280//!   - sslmode                  : `PREFERRED`
281//!   - statement-cache-capacity : `100`
282//!
283//! ## Customization
284//!
285//! To customize a database driver before its pool is created, use
286//! [`Database::custom()`]. The pool must implement [`Configurable`], as SQLx
287//! pools and MongoDB clients do. This method takes a function that receives a
288//! reference to the database's [`Config`] and the driver's configuration
289//! options, with Rocket's configuration and defaults already applied. The
290//! returned options are used to create the pool.
291//!
292//! For SQLx, the options are a tuple of pool and connection options. The pool
293//! options allow further customization via methods such as `after_connect()`.
294//! For MongoDB, the options are a `ClientOptions` structure. See
295//! [`Configurable::Options`] for the configuration types used by each driver.
296//! As an example, the following sets MongoDB's application name:
297//!
298//! ```rust
299//! # #[cfg(feature = "mongodb")] mod _inner {
300//! use rocket_db_pools::{mongodb, Database};
301//!
302//! #[derive(Database)]
303//! #[database("mongo_db")]
304//! struct Db(mongodb::Client);
305//!
306//! fn main() {
307//!     rocket::build().attach(Db::custom(|_config, mut options| {
308//!         options.app_name = Some("my-app".into());
309//!         options
310//!     }));
311//! }
312//! # }
313//! ```
314//!
315//! If configuration can fail, use [`Database::try_custom()`] instead. Returning
316//! an error from the callback aborts launch.
317//!
318//! ### SQLite Extensions
319//!
320//! SQLite extensions can be loaded via SQLx's
321//! `SqliteConnectOptions::extension()` method in a [`Database::custom()`]
322//! callback. The method is `unsafe`: the extension library must be trusted
323//! whenever a connection is created, including connections created after
324//! initialization. For example, to load the `rot13` extension:
325//!
326//! ```rust
327//! # #[cfg(feature = "sqlx_sqlite")] mod _inner {
328//! use rocket_db_pools::{sqlx, Database};
329//!
330//! #[derive(Database)]
331//! #[database("sqlite_db")]
332//! struct Db(sqlx::SqlitePool);
333//!
334//! fn main() {
335//!     rocket::build().attach(Db::custom(|_config, (pool, connection)| {
336//!         // SAFETY: this library is trusted for the pool's lifetime.
337//!         let connection = unsafe { connection.extension("rot13") };
338//!         (pool, connection)
339//!     }));
340//! }
341//! # }
342//! ```
343//!
344//! To use extension names from application configuration, capture the
345//! configuration in the callback.
346//!
347//! # Extending
348//!
349//! Any database driver can implement support for this library by implementing
350//! the [`Pool`] trait. To support customization via [`Database::custom()`],
351//! also implement [`Configurable`].
352
353#![doc(html_root_url = "https://api.rocket.rs/v0.5/rocket_db_pools")]
354#![doc(html_favicon_url = "https://rocket.rs/images/favicon.ico")]
355#![doc(html_logo_url = "https://rocket.rs/images/logo-boxed.png")]
356
357#![deny(missing_docs)]
358
359pub use rocket;
360
361/// Re-export of the `figment` crate.
362#[doc(inline)]
363pub use rocket::figment;
364
365#[cfg(any(feature = "diesel_postgres", feature = "diesel_mysql"))] pub mod diesel;
366#[cfg(feature = "deadpool_postgres")] pub use deadpool_postgres;
367#[cfg(feature = "deadpool_redis")] pub use deadpool_redis;
368#[cfg(feature = "mongodb")] pub use mongodb;
369#[cfg(feature = "sqlx")] pub use sqlx;
370
371mod database;
372mod error;
373mod pool;
374mod config;
375
376pub use self::database::{Connection, Database, Initializer};
377pub use self::error::Error;
378pub use self::pool::{Pool, Configurable};
379pub use self::config::Config;
380
381pub use rocket_db_pools_codegen::*;