Trait sea_orm_rocket::Database
source · [−]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 sea_orm_rocket::{Database};
#[derive(Database, Debug)]
#[database("sea_orm")]
struct Db(SeaOrmPool);
#[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 sea_orm_rocket::Database;
#[derive(Database)]
#[database("sea_orm")]
struct Db(SeaOrmPool);
#[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::fairing::{self, AdHoc};
use rocket::{Build, Rocket};
use sea_orm_rocket::Database;
#[derive(Database)]
#[database("sea_orm")]
struct Db(SeaOrmPool);
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))
}