Databases

While Rocket doesn’t have built-in support for databases yet, you can combine a few external libraries to get native-feeling access to databases in a Rocket application. Let’s take a look at how we might integrate Rocket with two common database libraries: diesel, a type-safe ORM and query builder, and r2d2, a library for connection pooling.

Our approach will be to have Rocket manage a pool of database connections using managed state and then implement a request guard that retrieves one connection. This will allow us to get access to the database in a handler by simply adding a DbConn argument:

  1. #[get("/users")]
  2. fn handler(conn: DbConn) { ... }

Dependencies

To get started, we need to depend on the diesel and r2d2 crates. For detailed information on how to use Diesel, please see the Diesel getting started guide. For this example, we use the following dependencies:

  1. [dependencies]
  2. rocket = "0.3.17"
  3. rocket_codegen = "0.3.17"
  4. diesel = { version = "<= 1.2", features = ["sqlite", "r2d2"] }

Your diesel dependency information may differ. The crates are imported as well:

  1. extern crate rocket;
  2. #[macro_use] extern crate diesel;

Managed Pool

The first step is to initialize a pool of database connections. The init_pool function below uses r2d2 to create a new pool of database connections. Diesel advocates for using a DATABASE_URL environment variable to set the database URL, and we use the same convention here. Excepting the long-winded types, the code is fairly straightforward: the DATABASE_URL environment variable is stored in the DATABASE_URL static, and an r2d2::Pool is created using the default configuration parameters and a Diesel SqliteConnection ConnectionManager.

  1. use diesel::sqlite::SqliteConnection;
  2. use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
  3. // An alias to the type for a pool of Diesel SQLite connections.
  4. type SqlitePool = Pool<ConnectionManager<SqliteConnection>>;
  5. // The URL to the database, set via the `DATABASE_URL` environment variable.
  6. static DATABASE_URL: &'static str = env!("DATABASE_URL");
  7. /// Initializes a database pool.
  8. fn init_pool() -> SqlitePool {
  9. let manager = ConnectionManager::<SqliteConnection>::new(DATABASE_URL);
  10. Pool::new(manager).expect("db pool")
  11. }

We then use managed state to have Rocket manage the pool for us:

  1. fn main() {
  2. rocket::ignite()
  3. .manage(init_pool())
  4. .launch();
  5. }

Connection Guard

The second and final step is to implement a request guard that retrieves a single connection from the managed connection pool. We create a new type, DbConn, that wraps an r2d2 pooled connection. We then implement FromRequest for DbConn so that we can use it as a request guard. Finally, we implement Deref with a target of SqliteConnection so that we can transparently use an &*DbConn as an &SqliteConnection.

  1. use std::ops::Deref;
  2. use rocket::http::Status;
  3. use rocket::request::{self, FromRequest};
  4. use rocket::{Request, State, Outcome};
  5. use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
  6. // Connection request guard type: a wrapper around an r2d2 pooled connection.
  7. pub struct DbConn(pub PooledConnection<ConnectionManager<SqliteConnection>>);
  8. /// Attempts to retrieve a single connection from the managed database pool. If
  9. /// no pool is currently managed, fails with an `InternalServerError` status. If
  10. /// no connections are available, fails with a `ServiceUnavailable` status.
  11. impl<'a, 'r> FromRequest<'a, 'r> for DbConn {
  12. type Error = ();
  13. fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
  14. let pool = request.guard::<State<SqlitePool>>()?;
  15. match pool.get() {
  16. Ok(conn) => Outcome::Success(DbConn(conn)),
  17. Err(_) => Outcome::Failure((Status::ServiceUnavailable, ()))
  18. }
  19. }
  20. }
  21. // For the convenience of using an &DbConn as an &SqliteConnection.
  22. impl Deref for DbConn {
  23. type Target = SqliteConnection;
  24. fn deref(&self) -> &Self::Target {
  25. &self.0
  26. }
  27. }

Usage

With these two pieces in place, we can use DbConn as a request guard in any handler or other request guard implementation, giving our application access to a database. As a simple example, we might write a route that returns a JSON array of some Task structures that are fetched from a database:

  1. #[get("/tasks")]
  2. fn get_tasks(conn: DbConn) -> QueryResult<Json<Vec<Task>>> {
  3. all_tasks.order(tasks::id.desc())
  4. .load::<Task>(&*conn)
  5. .map(|tasks| Json(tasks))
  6. }