Expand description
Asynchronous database driver connection pooling integration for Rocket.
§Quickstart
-
Add
rocket_db_poolsas a dependency with one or more database driver features enabled:[dependencies.rocket_db_pools] version = "0.2.0" features = ["sqlx_sqlite"] -
Choose a name for your database, here
sqlite_logs. Configure at least a URL for the database:[default.databases.sqlite_logs] url = "/path/to/database.sqlite" -
Derive
Databasefor a unit type (Logshere) which wraps the selected driver’sPooltype (see the driver table) and is decorated with#[database("name")]. AttachType::init()to your application’sRocketto initialize the database pool:use rocket_db_pools::{sqlx, Database}; #[derive(Database)] #[database("sqlite_logs")] struct Logs(sqlx::SqlitePool); #[launch] fn rocket() -> _ { rocket::build().attach(Logs::init()) } -
Use
Connection<Type>as a request guard to retrieve an active database connection, which dereferences to the native type in theConnectionderef column.use rocket_db_pools::Connection; use rocket_db_pools::sqlx::Row; #[get("/<id>")] async fn read(mut db: Connection<Logs>, id: i64) -> Option<Log> { sqlx::query("SELECT content FROM logs WHERE id = ?").bind(id) .fetch_one(&mut **db).await .and_then(|r| Ok(Log(r.try_get(0)?))) .ok() }Alternatively, use a reference to the database type as a request guard to retrieve the entire pool, but note that unlike retrieving a
Connection, doing so does not guarantee that a connection is available:use rocket_db_pools::sqlx::Row; #[get("/<id>")] async fn read(db: &Logs, id: i64) -> Option<Log> { sqlx::query("SELECT content FROM logs WHERE id = ?").bind(id) .fetch_one(&db.0).await .and_then(|r| Ok(Log(r.try_get(0)?))) .ok() }
§Supported Drivers
At present, this crate supports four drivers: deadpool, sqlx, mongodb, and diesel. Each driver may support multiple databases. Drivers have a varying degree of support for graceful shutdown, affected by the Type::init() fairing on Rocket shutdown.
§deadpool (v0.13)
| Database | Feature | Pool Type | Connection Deref |
|---|---|---|---|
| Postgres | deadpool_postgres (v0.13) | deadpool_postgres::Pool | deadpool_postgres::ClientWrapper |
| Redis | deadpool_redis (v0.15) | deadpool_redis::Pool | deadpool_redis::Connection |
On shutdown, new connections are denied. Shutdown does not wait for connections to be returned.
§sqlx (v0.7)
| Database | Feature | Pool Type | Connection Deref |
|---|---|---|---|
| Postgres | sqlx_postgres | sqlx::PgPool | sqlx::pool::PoolConnection<Postgres> |
| MySQL | sqlx_mysql | sqlx::MySqlPool | sqlx::pool::PoolConnection<MySql> |
| SQLite | sqlx_sqlite | sqlx::SqlitePool | sqlx::pool::PoolConnection<Sqlite> |
On shutdown, new connections are denied. Shutdown waits for connections to be returned.
§mongodb (v2)
| Database | Feature | Pool Type and Connection Deref |
|---|---|---|
| MongoDB | mongodb | mongodb::Client |
Graceful shutdown is not supported.
§diesel (v2)
| Database | Feature | Pool Type | Connection Deref |
|---|---|---|---|
| Postgres | diesel_postgres | diesel::PgPool | diesel::AsyncPgConnection |
| MySQL | diesel_mysql | diesel::MysqlPool | diesel::AsyncMysqlConnection |
See diesel for usage details.
On shutdown, new connections are denied. Shutdown does not wait for connections to be returned.
§Enabling Additional Driver Features
Only the minimal features for each driver crate are enabled by rocket_db_pools. To use additional driver functionality exposed via its crate’s features, you’ll need to depend on the crate directly with those features enabled in Cargo.toml:
[dependencies.sqlx] version = "0.7" default-features = false features = ["macros", "migrate"] [dependencies.rocket_db_pools] version = "0.2.0" features = ["sqlx_sqlite"]§Configuration
Configuration for a database named db_name is deserialized from a databases.db_name configuration parameter into a Config structure via Rocket’s configuration facilities. By default, configuration can be provided in Rocket.toml:
[default.databases.db_name] url = "db.sqlite" # Only `url` is required. These have sane defaults and are optional. min_connections = 64 max_connections = 1024 connect_timeout = 5 idle_timeout = 120 # This option is only supported by the `sqlx_sqlite` driver. extensions = ["memvfs", "rot13"]Or via environment variables:
ROCKET_DATABASES='{db_name={url="db.sqlite",idle_timeout=120}}'See Config for details on configuration parameters.
Note: deadpool and diesel drivers do not support and thus ignore the min_connections value.
§Driver Defaults
Some drivers provide configuration defaults different from the underlying database’s defaults. A best-effort attempt is made to document those differences below:
-
sqlx_sqlite- foreign keys :
enabled - journal mode :
WAL - create-missing :
enabled - synchronous :
full(even whenWAL) - busy timeout :
connection_timeout
- foreign keys :
-
sqlx_postgres- sslmode :
prefer - statement-cache-capacity :
100 - user : result of
whoami
- sslmode :
-
sqlx_mysql- sslmode :
PREFERRED - statement-cache-capacity :
100
- sslmode :
§Extending
Any database driver can implement support for this library by implementing the Pool trait.
Re-exports§
pub use rocket;pub use deadpool_postgres;pub use deadpool_redis;pub use mongodb;pub use sqlx;
Modules§
- diesel
- Re-export of
dieselwith prelude types overridden withasyncvariants fromdiesel_async. - figment
- Re-export of the
figmentcrate. Semi-hierarchical configuration so con-free, it’s unreal.
Structs§
- Config
- Base configuration for all database drivers.
- Connection
- A request guard which retrieves a single connection to a
Database. - Initializer
- A
Fairingwhich initializes aDatabaseand its connection pool.
Enums§
- Error
- A general error type for use by
Poolimplementors and returned by theConnectionrequest guard.
Traits§
- Database
- Derivable trait which ties a database
Poolwith a configuration name. - Pool
- Generic
Databasedriver connection pool trait.