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.4.0-rc.1"
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//! See [Postgres TLS](#postgres-tls) to connect to Postgres over TLS.
117//!
118//! ## `sqlx` (v0.9)
119//!
120//! | Database | Feature         | [`Pool`] Type        | [`Connection`] Deref                     |
121//! |----------|-----------------|----------------------|------------------------------------------|
122//! | Postgres | `sqlx_postgres` | [`sqlx::PgPool`]     | [`sqlx::pool::PoolConnection<Postgres>`] |
123//! | MySQL    | `sqlx_mysql`    | [`sqlx::MySqlPool`]  | [`sqlx::pool::PoolConnection<MySql>`]    |
124//! | SQLite   | `sqlx_sqlite`   | [`sqlx::SqlitePool`] | [`sqlx::pool::PoolConnection<Sqlite>`]   |
125//!
126//! [`sqlx::PgPool`]: https://docs.rs/sqlx/0.9/sqlx/type.PgPool.html
127//! [`sqlx::MySqlPool`]: https://docs.rs/sqlx/0.9/sqlx/type.MySqlPool.html
128//! [`sqlx::SqlitePool`]: https://docs.rs/sqlx/0.9/sqlx/type.SqlitePool.html
129//! [`sqlx::pool::PoolConnection<Postgres>`]: https://docs.rs/sqlx/0.9/sqlx/pool/struct.PoolConnection.html
130//! [`sqlx::pool::PoolConnection<MySql>`]: https://docs.rs/sqlx/0.9/sqlx/pool/struct.PoolConnection.html
131//! [`sqlx::pool::PoolConnection<Sqlite>`]: https://docs.rs/sqlx/0.9/sqlx/pool/struct.PoolConnection.html
132//!
133//! On shutdown, new connections are denied. Shutdown waits for connections to
134//! be returned.
135//!
136//! ## `mongodb` (v3)
137//!
138//! | Database | Feature   | [`Pool`] Type and [`Connection`] Deref |
139//! |----------|-----------|----------------------------------------|
140//! | MongoDB  | `mongodb` | [`mongodb::Client`]                    |
141//!
142//! Graceful shutdown is not supported.
143//!
144//! ## `diesel` (v2)
145//!
146//! | Database | Feature           | [`Pool`] Type          | [`Connection`] Deref                                        |
147//! |----------|-------------------|------------------------|-------------------------------------------------------------|
148//! | Postgres | `diesel_postgres` | [`diesel::PgPool`]     | [`diesel::AsyncPgConnection`]                               |
149//! | MySQL    | `diesel_mysql`    | [`diesel::MysqlPool`]  | [`diesel::AsyncMysqlConnection`]                            |
150//! | SQLite   | `diesel_sqlite`   | [`diesel::SqlitePool`] | [`diesel::SyncConnectionWrapper<diesel::SqliteConnection>`] |
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//! See [Postgres TLS](#postgres-tls) to connect to Postgres over TLS.
158//!
159//! ## Postgres TLS
160//!
161//! By default, the `deadpool_postgres` and `diesel_postgres` drivers connect
162//! _without_ TLS: a URL with `sslmode=require` fails to connect. To enable TLS
163//! for these drivers, also enable the `postgres_rustls_native_certs` feature:
164//!
165//! ```toml
166//! [dependencies.rocket_db_pools]
167//! version = "=0.4.0-rc.1"
168//! features = ["diesel_postgres", "postgres_rustls_native_certs"]
169//! ```
170//!
171//! To require TLS, set `sslmode=require` in the database URL. With
172//! `sslmode=prefer`, a connection without TLS is allowed if the server does not
173//! support TLS. The server's certificate and hostname are verified using the
174//! platform's native root certificates.
175//!
176//! To trust a private CA, set `SSL_CERT_FILE` to a PEM certificate bundle or
177//! `SSL_CERT_DIR` to a directory of PEM certificates. These replace the native
178//! roots. Errors loading certificates are logged. If no root certificates can
179//! be loaded, TLS connections fail.
180//!
181//! The `sqlx_postgres` driver supports TLS without additional features.
182//!
183//! ## Enabling Additional Driver Features
184//!
185//! Only the minimal features for each driver crate are enabled by
186//! `rocket_db_pools`. To use additional driver functionality exposed via its
187//! crate's features, you'll need to depend on the crate directly with those
188//! features enabled in `Cargo.toml`:
189//!
190//! ```toml
191//! [dependencies.sqlx]
192//! version = "0.9"
193//! default-features = false
194//! features = ["macros", "migrate"]
195//!
196//! [dependencies.rocket_db_pools]
197//! version = "=0.4.0-rc.1"
198//! features = ["sqlx_sqlite"]
199//! ```
200//!
201//! # Configuration
202//!
203//! Configuration for a database named `db_name` is deserialized from a
204//! `databases.db_name` configuration parameter into a [`Config`] structure via
205//! Rocket's [configuration facilities](rocket::config). By default,
206//! configuration can be provided in `Rocket.toml`:
207//!
208//! ```toml
209//! [default.databases.db_name]
210//! url = "db.sqlite"
211//!
212//! # Only `url` is required. These have sane defaults and are optional.
213//! min_connections = 64
214//! max_connections = 1024
215//! connect_timeout = 5
216//! idle_timeout = 120
217//! ```
218//!
219//! Or via environment variables:
220//!
221//! ```sh
222//! ROCKET_DATABASES='{db_name={url="db.sqlite",idle_timeout=120}}'
223//! ```
224//!
225//! See [`Config`] for details on configuration parameters.
226//!
227//! **Note:** `deadpool` and `diesel` drivers do not support and thus ignore the
228//! `min_connections` value. For these drivers, `idle_timeout` limits the time
229//! allowed to recycle a connection before reuse, including any health check.
230//! It does not close idle connections. By default, no timeout is set.
231//!
232//! ## Redis
233//!
234//! The `deadpool_redis` driver accepts an additional `response_timeout` option:
235//!
236//! ```toml
237//! [default.databases.redis]
238//! url = "redis://localhost:6379"
239//! response_timeout = 0.5
240//! ```
241//!
242//! This option limits how long the client waits for a command's response, in
243//! seconds, and defaults to `0.5`. Both integer and fractional values are
244//! accepted. Set `response_timeout = 0` to disable the timeout, for example,
245//! when using blocking commands such as `BLPOP`. A timeout does not cancel a
246//! command already executing on Redis. Negative, nonfinite, out-of-range, and
247//! nonnumeric values result in an [`Error::Config`] during initialization.
248//! Other drivers ignore this option.
249//!
250//! The Redis driver's connection timeout is disabled. Instead, Deadpool limits
251//! both the time spent waiting for a pooled connection and the time spent
252//! creating a connection to [`Config::connect_timeout`] seconds each. These
253//! limits apply separately. Redis health checks also use `response_timeout`,
254//! even when `idle_timeout` is unset.
255//!
256//! ## Driver Defaults
257//!
258//! Some drivers provide configuration defaults different from the underlying
259//! database's defaults. A best-effort attempt is made to document those
260//! differences below:
261//!
262//! * `deadpool_redis`
263//!
264//!   - response timeout   : `0.5` seconds
265//!   - connection timeout : disabled (Deadpool's creation timeout applies)
266//!
267//! * `sqlx_sqlite`
268//!
269//!   - foreign keys   : `enabled`
270//!   - journal mode   : `WAL`
271//!   - create-missing :  `enabled`
272//!   - synchronous    : `full` (even when `WAL`)
273//!   - busy timeout   : `connect_timeout`
274//!
275//! * `sqlx_postgres`
276//!
277//!   - sslmode                  : `prefer`
278//!   - statement-cache-capacity : `100`
279//!   - user                     : result of `whoami`
280//!
281//! * `sqlx_mysql`
282//!
283//!   - sslmode                  : `PREFERRED`
284//!   - statement-cache-capacity : `100`
285//!
286//! ## Customization
287//!
288//! To customize a database driver before its pool is created, use
289//! [`Database::custom()`]. The pool must implement [`Configurable`], as SQLx
290//! pools and MongoDB clients do. This method takes a function that receives a
291//! reference to the database's [`Config`] and the driver's configuration
292//! options, with Rocket's configuration and defaults already applied. The
293//! returned options are used to create the pool.
294//!
295//! For SQLx, the options are a tuple of pool and connection options. The pool
296//! options allow further customization via methods such as `after_connect()`.
297//! For MongoDB, the options are a `ClientOptions` structure. See
298//! [`Configurable::Options`] for the configuration types used by each driver.
299//! As an example, the following sets MongoDB's application name:
300//!
301//! ```rust
302//! # #[cfg(feature = "mongodb")] mod _inner {
303//! use rocket_db_pools::{mongodb, Database};
304//!
305//! #[derive(Database)]
306//! #[database("mongo_db")]
307//! struct Db(mongodb::Client);
308//!
309//! fn main() {
310//!     rocket::build().attach(Db::custom(|_config, mut options| {
311//!         options.app_name = Some("my-app".into());
312//!         options
313//!     }));
314//! }
315//! # }
316//! ```
317//!
318//! If configuration can fail, use [`Database::try_custom()`] instead. Returning
319//! an error from the callback aborts launch.
320//!
321//! ### SQLite Extensions
322//!
323//! SQLite extensions can be loaded via SQLx's
324//! `SqliteConnectOptions::extension()` method in a [`Database::custom()`]
325//! callback. The method is `unsafe`: the extension library must be trusted
326//! whenever a connection is created, including connections created after
327//! initialization. For example, to load the `rot13` extension:
328//!
329//! ```rust
330//! # #[cfg(feature = "sqlx_sqlite")] mod _inner {
331//! use rocket_db_pools::{sqlx, Database};
332//!
333//! #[derive(Database)]
334//! #[database("sqlite_db")]
335//! struct Db(sqlx::SqlitePool);
336//!
337//! fn main() {
338//!     rocket::build().attach(Db::custom(|_config, (pool, connection)| {
339//!         // SAFETY: this library is trusted for the pool's lifetime.
340//!         let connection = unsafe { connection.extension("rot13") };
341//!         (pool, connection)
342//!     }));
343//! }
344//! # }
345//! ```
346//!
347//! To use extension names from application configuration, capture the
348//! configuration in the callback.
349//!
350//! # Extending
351//!
352//! Any database driver can implement support for this library by implementing
353//! the [`Pool`] trait. To support customization via [`Database::custom()`],
354//! also implement [`Configurable`].
355
356#![doc(html_root_url = "https://api.rocket.rs/v0.6-rc/rocket_db_pools")]
357#![doc(html_favicon_url = "https://rocket.rs/images/favicon.ico")]
358#![doc(html_logo_url = "https://rocket.rs/images/logo-boxed.png")]
359
360#![deny(missing_docs)]
361
362pub use rocket;
363
364/// Re-export of the `figment` crate.
365#[doc(inline)]
366pub use rocket::figment;
367
368#[cfg(any(
369    feature = "diesel_postgres",
370    feature = "diesel_mysql",
371    feature = "diesel_sqlite"
372))] pub mod diesel;
373#[cfg(feature = "deadpool_postgres")] pub use deadpool_postgres;
374#[cfg(feature = "deadpool_redis")] pub use deadpool_redis;
375#[cfg(feature = "mongodb")] pub use mongodb;
376#[cfg(feature = "sqlx")] pub use sqlx;
377
378mod database;
379mod error;
380mod pool;
381mod config;
382
383pub use self::database::{Connection, Database, Initializer};
384pub use self::error::Error;
385pub use self::pool::{Pool, Configurable};
386pub use self::config::Config;
387
388pub use rocket_db_pools_codegen::*;