Crate gotham_middleware_diesel
source · [−]Expand description
Provides an interface for running Diesel queries in a Gotham application.
The gotham diesel middleware uses tokio::task::spawn_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.
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) -> Pin<Box<HandlerFuture>> {
let repo = Repo::borrow_from(&state).clone();
// As an example, we perform the query:
// `SELECT 1`
async move {
let result = repo
.run(move |conn| {
diesel::select(diesel::dsl::sql("1"))
.load::<i64>(&conn)
.map(|v| v.into_iter().next().expect("no results"))
})
.await;
match result {
Ok(n) => {
let body = format!("result: {}", n);
let res = create_response(&state, StatusCode::OK, TEXT_PLAIN, body);
Ok((state, res))
}
Err(e) => Err((state, e.into())),
}
}
.boxed()
}
Structs
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.
A database “repository”, for running database workloads. Manages a connection pool and running blocking tasks using tokio::task::spawn_blocking which does not block the tokio event loop.