Skip to main content

Database

Trait 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 custom<F>(f: F) -> Initializer<Self>
       where Self::Pool: Configurable,
             F: Fn(&Config, <Self::Pool as Configurable>::Options) -> <Self::Pool as Configurable>::Options + Send + Sync + 'static { ... }
    fn try_custom<F>(f: F) -> Initializer<Self>
       where Self::Pool: Configurable,
             F: Fn(&Config, <Self::Pool as Configurable>::Options) -> Result<<Self::Pool as Configurable>::Options, <Self::Pool as Pool>::Error> + Send + Sync + 'static { ... }
    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§

Source

const NAME: &'static str

The configuration name for this database.

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

Required Associated Types§

Source

type Pool: Pool

The Pool type of connections to this database.

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

Provided Methods§

Source

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())
}
Source

fn custom<F>(f: F) -> Initializer<Self>
where Self::Pool: Configurable, F: Fn(&Config, <Self::Pool as Configurable>::Options) -> <Self::Pool as Configurable>::Options + Send + Sync + 'static,

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

Unlike Self::init(), this method allows you to configure the database driver via the function f. The pool must implement Configurable. See Configurable::Options for the configuration types used by each driver.

The function f is called with a reference to the database’s Config and the driver’s options after applying Rocket’s configuration and defaults. The returned options are used to create the pool, overriding any previously configured values.

This method does not allow the function f to fail. If f is fallible, use Self::try_custom() instead.

§Example
use std::time::Duration;
use rocket_db_pools::{sqlx, Database};

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

fn main() {
    rocket::build().attach(Db::custom(|_config, (pool, connection)| {
        (pool, connection.busy_timeout(Duration::from_secs(10)))
    }));
}
Source

fn try_custom<F>(f: F) -> Initializer<Self>
where Self::Pool: Configurable, F: Fn(&Config, <Self::Pool as Configurable>::Options) -> Result<<Self::Pool as Configurable>::Options, <Self::Pool as Pool>::Error> + Send + Sync + 'static,

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

This variant of Self::custom() allows a fallible f. The error type is the pool’s Pool::Error. If f returns an error during initialization, it will cancel the launch.

Source

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 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))
}

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§