Crate rocket_db_pools

source ·
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"
    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 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)

DatabaseFeaturePool TypeConnection Deref
Postgresdeadpool_postgres (v0.13)deadpool_postgres::Pooldeadpool_postgres::ClientWrapper
Redisdeadpool_redis (v0.15)deadpool_redis::Pooldeadpool_redis::Connection

On shutdown, new connections are denied. Shutdown does not wait for connections to be returned.

§sqlx (v0.7)

On shutdown, new connections are denied. Shutdown waits for connections to be returned.

§mongodb (v2)

DatabaseFeaturePool Type and Connection Deref
MongoDBmongodbmongodb::Client

Graceful shutdown is not supported.

§diesel (v2)

DatabaseFeaturePool TypeConnection Deref
Postgresdiesel_postgresdiesel::PgPooldiesel::AsyncPgConnection
MySQLdiesel_mysqldiesel::MysqlPooldiesel::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.1.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 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 library by implementing the Pool trait.

Re-exports§

Modules§

  • Re-export of diesel with prelude types overridden with async variants from diesel_async.
  • Re-export of the figment crate. Semi-hierarchical configuration so con-free, it’s unreal.

Structs§

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§