logo
pub trait Database: From<Self::Pool> + DerefMut<Target = Self::Pool> + Send + Sync + 'static {
    type Pool: Pool;

    const NAME: &'static str;

    fn init() -> Initializer<Self> { ... }
    fn fetch<P: Phase>(rocket: &Rocket<P>) -> Option<&Self> { ... }
}
Expand description

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

This trait should rarely, if ever, be implemented manually. Instead, it should be derived:

use rocket_db_pools::{deadpool_redis, Database};

#[derive(Database)]
#[database("memdb")]
struct Db(deadpool_redis::Pool);

#[launch]
fn rocket() -> _ {
    rocket::build().attach(Db::init())
}

See the Database derive for details.

Required Associated Types

The Pool type of connections to this database.

When Database is derived, this takes the value of the Inner type in struct Db(Inner).

Required Associated Constants

The configuration name for this database.

When Database is derived, this takes the value "name" in the #[database("name")] attribute.

Provided Methods

Returns a fairing that initializes the database and its connection pool.

Example
use rocket_db_pools::{deadpool_postgres, Database};

#[derive(Database)]
#[database("pg_db")]
struct Db(deadpool_postgres::Pool);

#[launch]
fn rocket() -> _ {
    rocket::build().attach(Db::init())
}

Returns a reference to the initialized database in rocket. The initializer fairing returned by init() must have already executed for Option to be Some. This is guaranteed to be the case if the fairing is attached and either:

  • Rocket is in the Orbit phase. That is, the application is running. This is always the case in request guards and liftoff fairings,
  • or Rocket is in the Build or Ignite phase and the Initializer fairing has already been run. This is the case in all fairing callbacks corresponding to fairings attached after the Initializer fairing.
Example

Run database migrations in an ignite fairing. It is imperative that the migration fairing be registered after the init() fairing.

use rocket::{Rocket, Build};
use rocket::fairing::{self, AdHoc};

use rocket_db_pools::{sqlx, Database};

#[derive(Database)]
#[database("sqlite_db")]
struct Db(sqlx::SqlitePool);

async fn run_migrations(rocket: Rocket<Build>) -> fairing::Result {
    if let Some(db) = Db::fetch(&rocket) {
        // run migrations using `db`. get the inner type with &db.0.
        Ok(rocket)
    } else {
        Err(rocket)
    }
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .attach(Db::init())
        .attach(AdHoc::try_on_ignite("DB Migrations", run_migrations))
}

Implementors