Trait rocket_db_pools::Database
source · 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 Types§
Required Associated Constants§
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
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
orIgnite
phase and theInitializer
fairing has already been run. This is the case in all fairing callbacks corresponding to fairings attached after theInitializer
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))
}
Object Safety§
This trait is not object safe.