I'm currently trying to learn async, and I'm building a simple webapp using tide and sqlx.
I'm trying to get a route endpoint to perform an SQL query and return the result, but when this route is accessed, sqlx panics with the message "this functionality requires a Tokio context".
Clearly I am not understanding somethng important about async here, can you help me understand what I don't understand and how to fix this please:
#[tokio::main]
async fn main() -> tide::Result<()> {
//...
let mut app: Server<State> = Server::with_state(State { db_pool });
let rows = query!("select 1 as one").fetch_one(&db_pool).await?;
//this works fine
app.at("/").get(|req: Request<State>| async move {
let db_pool = &req.state().db_pool;
let rows = query!("select 1 as one").fetch_one(db_pool).await?;
//this panics
});
}
The State struct just contains a reference to the db_pool.
I am not familiar with these libraries. But for learning async, I have the feeling you're making things more difficult by choosing a web framework written for async_std and using it with tokio. To reduce the number of things you have to deal with as you learn, you may want to choose a matching pair: tokio with axum (or others written for tokio), or async_std with tide.
You might as well post the full backtrace in case someone more familiar with these libraries takes a look.
Ahh, I didn't realise that could be an issue. It seems like the tide framework is indeed written for async_std. I switched to using that and my example works fine now! Many thanks!
Yes. But I can't tell whether there is a way to make tide work with tokio or not. There are some older tide github issues saying it doesn't work, but this one says tide can be useed with async_std 1.9, which allows it to work with tokio:
See "Tokio 1.0 compat" section in the 1.9 release notes. There is a tokio1 feature flag that can be set. So this means you would need to specify both async-std and tokio as dependencies, so that tide would use the version of async_std with the tokio feature flag.
In any case, for learning I'm sure it is easier to use tide with async_std.