[][src]Crate gotham_middleware_diesel

Provides an interface for running Diesel queries in a Gotham application.

The gotham diesel middleware uses tokio_threadpool::blocking, which allows blocking operations to run without blocking the tokio reactor. Although not true async, this allows multiple concurrent database requests to be handled, with a default of 100 concurrent blocking operations. For further details see tokio_threadpool::blocking documentation.

Usage example:


pub type Repo = gotham_middleware_diesel::Repo<SqliteConnection>;

fn router() -> Router {
    // Create a Repo - using an in memory Sqlite DB
    let repo = Repo::new(":memory:");
    // Add the diesel middleware to a new pipeline
    let (chain, pipeline) =
        single_pipeline(new_pipeline().add(DieselMiddleware::new(repo)).build());

    // Build the router
    build_router(chain, pipeline, |route| {
        route.get("/").to(handler);
    })
}

fn handler(state: State) -> Box<HandlerFuture> {
    let repo = Repo::borrow_from(&state).clone();
    // As an example, we perform the query:
    // `SELECT 1`
    let f = repo
        .run(move |conn| {
            diesel::select(diesel::dsl::sql("1"))
            .load::<i64>(&conn)
            .map(|v| v.into_iter().next().expect("no results"))
        }).then(|result| match result {
           Ok(n) => {
               let body = format!("result: {}", n);
               let res = create_response(&state, StatusCode::OK, mime::TEXT_PLAIN, body);
               Ok((state, res))
           },
           Err(e) => Err((state, e.into_handler_error())),
        });
   Box::new(f)
}

Structs

DieselMiddleware

A Gotham compatible Middleware that manages a pool of Diesel connections via a Repo and hands out connections to other Middleware and Handlers that require them via the Gotham State mechanism.

Repo

A database "repository", for running database workloads. Manages a connection pool and running blocking tasks using tokio_threadpool::blocking which does not block the tokio event loop.