rocket_db_pools_community/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//! package = "rocket_db_pools-community"
11//! version = "0.3.2"
12//! features = ["sqlx_sqlite"]
13//! ```
14//!
15//! 2. Choose a name for your database, here `sqlite_logs`.
16//! [Configure](#configuration) _at least_ a URL for the database:
17//!
18//! ```toml
19//! [default.databases.sqlite_logs]
20//! url = "/path/to/database.sqlite"
21//! ```
22//!
23//! 3. [Derive](derive@Database) [`Database`] for a unit type (`Logs` here)
24//! which wraps the selected driver's [`Pool`] type (see [the driver
25//! table](#supported-drivers)) and is decorated with `#[database("name")]`.
26//! Attach `Type::init()` to your application's `Rocket` to initialize the
27//! database pool:
28//!
29//! ```rust
30//! # extern crate rocket_db_pools_community as rocket_db_pools;
31//! # #[cfg(feature = "sqlx_sqlite")] mod _inner {
32//! # use rocket::launch;
33//! use rocket_db_pools::{sqlx, Database};
34//!
35//! #[derive(Database)]
36//! #[database("sqlite_logs")]
37//! struct Logs(sqlx::SqlitePool);
38//!
39//! #[launch]
40//! fn rocket() -> _ {
41//! rocket::build().attach(Logs::init())
42//! }
43//! # }
44//! ```
45//!
46//! 4. Use [`Connection<Type>`](Connection) as a request guard to retrieve an
47//! active database connection, which dereferences to the native type in the
48//! [`Connection` deref](#supported-drivers) column.
49//!
50//! ```rust
51//! # extern crate rocket_db_pools_community as rocket_db_pools;
52//! # #[cfg(feature = "sqlx_sqlite")] mod _inner {
53//! # use rocket::{get, response::Responder};
54//! # use rocket_db_pools::{sqlx, Database};
55//! # #[derive(Database)]
56//! # #[database("sqlite_logs")]
57//! # struct Logs(sqlx::SqlitePool);
58//! #
59//! # #[derive(Responder)]
60//! # struct Log(String);
61//! #
62//! use rocket_db_pools::Connection;
63//! use rocket_db_pools::sqlx::Row;
64//!
65//! #[get("/<id>")]
66//! async fn read(mut db: Connection<Logs>, id: i64) -> Option<Log> {
67//! sqlx::query("SELECT content FROM logs WHERE id = ?").bind(id)
68//! .fetch_one(&mut **db).await
69//! .and_then(|r| Ok(Log(r.try_get(0)?)))
70//! .ok()
71//! }
72//! # }
73//! ```
74//!
75//! Alternatively, use a reference to the database type as a request guard to
76//! retrieve the entire pool, but note that unlike retrieving a `Connection`,
77//! doing so does _not_ guarantee that a connection is available:
78//!
79//! ```rust
80//! # extern crate rocket_db_pools_community as rocket_db_pools;
81//! # #[cfg(feature = "sqlx_sqlite")] mod _inner {
82//! # use rocket::{get, response::Responder};
83//! # use rocket_db_pools::{sqlx, Database};
84//! # #[derive(Database)]
85//! # #[database("sqlite_logs")]
86//! # struct Logs(sqlx::SqlitePool);
87//! #
88//! # #[derive(Responder)]
89//! # struct Log(String);
90//! #
91//! use rocket_db_pools::sqlx::Row;
92//!
93//! #[get("/<id>")]
94//! async fn read(db: &Logs, id: i64) -> Option<Log> {
95//! sqlx::query("SELECT content FROM logs WHERE id = ?").bind(id)
96//! .fetch_one(&db.0).await
97//! .and_then(|r| Ok(Log(r.try_get(0)?)))
98//! .ok()
99//! }
100//! # }
101//! ```
102//!
103//! # Supported Drivers
104//!
105//! At present, this crate supports _four_ drivers: [`deadpool`], [`sqlx`],
106//! [`mongodb`], and [`diesel`]. Each driver may support multiple databases.
107//! Drivers have a varying degree of support for graceful shutdown, affected by
108//! the `Type::init()` fairing on Rocket shutdown.
109//!
110//! ## `deadpool` (v0.12)
111//!
112//! | Database | Feature | [`Pool`] Type | [`Connection`] Deref |
113//! |----------|-----------------------------|-----------------------------|--------------------------------------|
114//! | Postgres | `deadpool_postgres` (v0.14) | [`deadpool_postgres::Pool`] | [`deadpool_postgres::ClientWrapper`] |
115//! | Redis | `deadpool_redis` (v0.16) | [`deadpool_redis::Pool`] | [`deadpool_redis::Connection`] |
116//!
117//! On shutdown, new connections are denied. Shutdown _does not_ wait for
118//! connections to be returned.
119//!
120//! ## `sqlx` (v0.7)
121//!
122//! | Database | Feature | [`Pool`] Type | [`Connection`] Deref |
123//! |----------|-----------------|----------------------|------------------------------------------|
124//! | Postgres | `sqlx_postgres` | [`sqlx::PgPool`] | [`sqlx::pool::PoolConnection<Postgres>`] |
125//! | MySQL | `sqlx_mysql` | [`sqlx::MySqlPool`] | [`sqlx::pool::PoolConnection<MySql>`] |
126//! | SQLite | `sqlx_sqlite` | [`sqlx::SqlitePool`] | [`sqlx::pool::PoolConnection<Sqlite>`] |
127//!
128//! [`sqlx::PgPool`]: https://docs.rs/sqlx/0.6/sqlx/type.PgPool.html
129//! [`sqlx::MySqlPool`]: https://docs.rs/sqlx/0.6/sqlx/type.MySqlPool.html
130//! [`sqlx::SqlitePool`]: https://docs.rs/sqlx/0.6/sqlx/type.SqlitePool.html
131//! [`sqlx::pool::PoolConnection<Postgres>`]: https://docs.rs/sqlx/0.6/sqlx/pool/struct.PoolConnection.html
132//! [`sqlx::pool::PoolConnection<MySql>`]: https://docs.rs/sqlx/0.6/sqlx/pool/struct.PoolConnection.html
133//! [`sqlx::pool::PoolConnection<Sqlite>`]: https://docs.rs/sqlx/0.6/sqlx/pool/struct.PoolConnection.html
134//!
135//! On shutdown, new connections are denied. Shutdown waits for connections to
136//! be returned.
137//!
138//! ## `mongodb` (v3)
139//!
140//! | Database | Feature | [`Pool`] Type and [`Connection`] Deref |
141//! |----------|-----------|----------------------------------------|
142//! | MongoDB | `mongodb` | [`mongodb::Client`] |
143//!
144//! Graceful shutdown is not supported.
145//!
146//! ## `diesel` (v2)
147//!
148//! | Database | Feature | [`Pool`] Type | [`Connection`] Deref |
149//! |----------|-------------------|------------------------|--------------------------------------------------------------|
150//! | Postgres | `diesel_postgres` | [`diesel::PgPool`] | [`diesel::AsyncPgConnection`] |
151//! | MySQL | `diesel_mysql` | [`diesel::MysqlPool`] | [`diesel::AsyncMysqlConnection`] |
152//! | SQLite | `diesel_sqlite` | [`diesel::SqlitePool`] | [`diesel::SyncConnectionWrapper<diesel::SqliteConnection>>`] |
153//!
154//! See [`diesel`] for usage details.
155//!
156//! On shutdown, new connections are denied. Shutdown _does not_ wait for
157//! connections to be returned.
158//!
159//! ## Enabling Additional Driver Features
160//!
161//! Only the minimal features for each driver crate are enabled by
162//! `rocket_db_pools`. To use additional driver functionality exposed via its
163//! crate's features, you'll need to depend on the crate directly with those
164//! features enabled in `Cargo.toml`:
165//!
166//! ```toml
167//! [dependencies.sqlx]
168//! version = "0.7"
169//! default-features = false
170//! features = ["macros", "migrate"]
171//!
172//! [dependencies.rocket_db_pools]
173//! package = "rocket_db_pools-community"
174//! version = "0.3.2"
175//! features = ["sqlx_sqlite"]
176//! ```
177//!
178//! # Configuration
179//!
180//! Configuration for a database named `db_name` is deserialized from a
181//! `databases.db_name` configuration parameter into a [`Config`] structure via
182//! Rocket's [configuration facilities](rocket::config). By default,
183//! configuration can be provided in `Rocket.toml`:
184//!
185//! ```toml
186//! [default.databases.db_name]
187//! url = "db.sqlite"
188//!
189//! # Only `url` is required. These have sane defaults and are optional.
190//! min_connections = 64
191//! max_connections = 1024
192//! connect_timeout = 5
193//! idle_timeout = 120
194//!
195//! # This option is only supported by the `sqlx_sqlite` driver.
196//! extensions = ["memvfs", "rot13"]
197//! ```
198//!
199//! Or via environment variables:
200//!
201//! ```sh
202//! ROCKET_DATABASES='{db_name={url="db.sqlite",idle_timeout=120}}'
203//! ```
204//!
205//! See [`Config`] for details on configuration parameters.
206//!
207//! **Note:** `deadpool` and `diesel` drivers do not support and thus ignore the
208//! `min_connections` value.
209//!
210//! ## Driver Defaults
211//!
212//! Some drivers provide configuration defaults different from the underlying
213//! database's defaults. A best-effort attempt is made to document those
214//! differences below:
215//!
216//! * `sqlx_sqlite`
217//!
218//! - foreign keys : `enabled`
219//! - journal mode : `WAL`
220//! - create-missing : `enabled`
221//! - synchronous : `full` (even when `WAL`)
222//! - busy timeout : `connection_timeout`
223//!
224//! * `sqlx_postgres`
225//!
226//! - sslmode : `prefer`
227//! - statement-cache-capacity : `100`
228//! - user : result of `whoami`
229//!
230//! * `sqlx_mysql`
231//!
232//! - sslmode : `PREFERRED`
233//! - statement-cache-capacity : `100`
234//!
235//! # Extending
236//!
237//! Any database driver can implement support for this library by implementing
238//! the [`Pool`] trait.
239
240#![doc(html_root_url = "https://api.rocket.rs/master/rocket_db_pools")]
241#![doc(html_favicon_url = "https://rocket.rs/images/favicon.ico")]
242#![doc(html_logo_url = "https://rocket.rs/images/logo-boxed.png")]
243#![deny(missing_docs)]
244
245pub use rocket;
246
247/// Re-export of the `figment` crate.
248#[doc(inline)]
249pub use rocket::figment;
250
251#[cfg(any(
252 feature = "diesel_postgres",
253 feature = "diesel_mysql",
254 feature = "diesel_sqlite"
255))]
256pub mod diesel;
257#[cfg(feature = "deadpool_postgres")]
258pub use deadpool_postgres;
259#[cfg(feature = "deadpool_redis")]
260pub use deadpool_redis;
261#[cfg(feature = "mongodb")]
262pub use mongodb;
263#[cfg(feature = "sqlx")]
264pub use sqlx;
265
266mod config;
267mod database;
268mod error;
269mod pool;
270
271pub use self::config::Config;
272pub use self::database::{Connection, Database, Initializer};
273pub use self::error::Error;
274pub use self::pool::Pool;
275
276pub use rocket_db_pools_codegen::*;