Skip to content

Instantly share code, notes, and snippets.

@edgarogh
Created April 13, 2021 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edgarogh/21ef8c1fcf74e04bbe251e9a1dc32ab8 to your computer and use it in GitHub Desktop.
Save edgarogh/21ef8c1fcf74e04bbe251e9a1dc32ab8 to your computer and use it in GitHub Desktop.
[MIT License 2021 Edgar ONGHENA] Extension trait to use Diesel ORM asynchronously with rocket 0.5 and rocket_contrib 0.5
/* Copyright Edgar ONGHENA 2021. All Rights Reserved.
This file is licensed under the MIT License.
License text available at https://opensource.org/licenses/MIT
This header may be removed if the terms of the license are still respected
(including, but not limited to, giving proper credit somewhere else) */
use diesel::dsl::Limit;
use diesel::query_dsl::limit_dsl::LimitDsl;
use diesel::query_dsl::LoadQuery;
use diesel::{QueryResult, RunQueryDsl};
type ConnWrapper = crate::FIXME;
type Conn = rocket_contrib::databases::diesel::PgConnection;
#[rocket::async_trait]
pub trait AsyncRunQueryDsl {
async fn load_async<U>(self, conn: &ConnWrapper) -> QueryResult<Vec<U>>
where
Self: LoadQuery<Conn, U>,
QueryResult<Vec<U>>: 'static + Send;
async fn get_result_async<U>(self, conn: &ConnWrapper) -> QueryResult<U>
where
Self: LoadQuery<Conn, U>,
QueryResult<U>: 'static + Send;
async fn get_results_async<U>(self, conn: &ConnWrapper) -> QueryResult<Vec<U>>
where
Self: LoadQuery<Conn, U>,
QueryResult<Vec<U>>: 'static + Send;
async fn first_async<U>(self, conn: &ConnWrapper) -> QueryResult<U>
where
Self: LimitDsl,
Limit<Self>: LoadQuery<Conn, U>,
QueryResult<U>: 'static + Send;
}
#[rocket::async_trait]
impl<T: 'static + Send + RunQueryDsl<Conn>> AsyncRunQueryDsl for T {
async fn load_async<U>(self, conn: &ConnWrapper) -> QueryResult<Vec<U>>
where
Self: LoadQuery<Conn, U>,
QueryResult<Vec<U>>: 'static + Send,
{
conn.run(move |db| self.load(db)).await
}
async fn get_result_async<U>(self, conn: &ConnWrapper) -> QueryResult<U>
where
Self: LoadQuery<Conn, U>,
QueryResult<U>: 'static + Send,
{
conn.run(move |db| self.get_result(db)).await
}
async fn get_results_async<U>(self, conn: &ConnWrapper) -> QueryResult<Vec<U>>
where
Self: LoadQuery<Conn, U>,
QueryResult<Vec<U>>: 'static + Send,
{
conn.run(move |db| self.get_results(db)).await
}
async fn first_async<U>(self, conn: &ConnWrapper) -> QueryResult<U>
where
Self: LimitDsl,
Limit<Self>: LoadQuery<Conn, U>,
QueryResult<U>: 'static + Send,
{
conn.run(move |db| self.first(db)).await
}
}
@edgarogh
Copy link
Author

Usage: import the trait and add _async behind any of the load, get_result, get_results or first methods in any diesel request. Don't forget to .await the returned value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment