pub trait Database:
From<Self::Pool>
+ DerefMut<Target = Self::Pool>
+ Send
+ Sync
+ 'static {
type Pool: Pool;
const NAME: &'static str;
// Provided methods
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 Constants§
Required Associated Types§
Provided Methods§
Sourcefn init() -> Initializer<Self>
fn init() -> Initializer<Self>
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())
}Sourcefn fetch<P: Phase>(rocket: &Rocket<P>) -> Option<&Self>
fn fetch<P: Phase>(rocket: &Rocket<P>) -> Option<&Self>
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
Orbitphase. That is, the application is running. This is always the case in request guards and liftoff fairings, - or Rocket is in the
BuildorIgnitephase and theInitializerfairing has already been run. This is the case in all fairing callbacks corresponding to fairings attached after theInitializerfairing.
§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))
}Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.