logo
Expand description

Asynchronous database driver connection pooling integration for Rocket.

Quickstart

  1. Add rocket_db_pools as a dependency with one or more database driver features enabled:

    [dependencies.rocket_db_pools]
    version = "0.1.0-rc.2"
    features = ["sqlx_sqlite"]
  2. 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"
  3. Derive Database for a unit type (Logs here) which wraps the selected driver’s Pool type (see the driver table) and is decorated with #[database("name")]. Attach Type::init() to your application’s Rocket to 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())
    }
  4. Use Connection<Type> as a request guard to retrieve an active database connection, which dereferences to the native type in the Connection deref 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 three drivers: deadpool, sqlx, and mongodb. Each driver may support multiple databases.

deadpool (v0.9)

sqlx (v0.5)

DatabaseFeaturePool TypeConnection Deref
Postgressqlx_postgressqlx::PgPool[sqlx::pool::PoolConnection<Postgres>]
MySQLsqlx_mysqlsqlx::MySqlPool[sqlx::pool::PoolConnection<MySql>]
SQLitesqlx_sqlitesqlx::SqlitePool[sqlx::pool::PoolConnection<Sqlite>]
MSSQLsqlx_mssqlsqlx::MssqlPool[sqlx::pool::PoolConnection<Mssql>]

mongodb (v2)

DatabaseFeaturePool Type and Connection Deref
MongoDBmongodbmongodb::Client

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.5"
default-features = false
features = ["macros", "offline", "migrate"]

[dependencies.rocket_db_pools]
version = "0.1.0-rc.2"
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"

min_connections = 64
max_connections = 1024
connect_timeout = 5
idle_timeout = 120

Or via environment variables:

ROCKET_DATABASES='{db_name={url="db.sqlite",idle_timeout=120}}'

See Config for details on configuration parameters.

Note: deadpool drivers do not support and thus ignore the min_connections value.

Driver Defaults

Some drivers provide configuration defaults different from the underyling 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 when WAL)
    • busy timeout : connection_timeout
  • sqlx_postgres

    • sslmode : prefer
    • statement-cache-capacity : 100
    • user : result of whoami
  • sqlx_mysql

    • sslmode : PREFERRED
    • statement-cache-capacity : 100

Extending

Any database driver can implement support for this libary by implementing the Pool trait.

Re-exports

pub use rocket;
pub use mongodb;
pub use sqlx;

Modules

Re-export of the figment crate. Semi-hierarchical configuration so con-free, it’s unreal.

Structs

Base configuration for all database drivers.

A request guard which retrieves a single connection to a Database.

A Fairing which initializes a Database and its connection pool.

Enums

A general error type for use by Pool implementors and returned by the Connection request guard.

Traits

Derivable trait which ties a database Pool with a configuration name.

Generic Database driver connection pool trait.

Derive Macros

Automatic derive for the Database trait.