Quantcast
Channel: Active questions tagged r2d2 - Stack Overflow
Viewing all articles
Browse latest Browse all 12

How to use DB connections in Actix several times per function?

$
0
0

At https://actix.rs/docs/databases/ there is an example:

async fn index(pool: web::Data<DbPool>, name: web::Path<(String)>) -> impl Responder {    let name = name.into_inner();    let conn = pool.get().expect("couldn't get db connection from pool");    let user = web::block(move || actions::insert_new_user(&conn, &user))        .await        .map_err(|e| {            eprintln!("{}", e);            HttpResponse::InternalServerError().finish()        })?;    Ok(HttpResponse::Ok().json(user))}

What to do if I need several SQL queries in one function? The following obviously won't work due to moving conn:

async fn index(pool: web::Data<DbPool>, name: web::Path<(String)>) -> impl Responder {    let name = name.into_inner();    let conn = pool.get().expect("couldn't get db connection from pool");    let user1 = web::block(move || actions::insert_new_user(&conn, &user))        .await        .map_err(|e| {            eprintln!("{}", e);            HttpResponse::InternalServerError().finish()        })?;    // ... asynchronous code here    let user2 = web::block(move || actions::insert_new_user(&conn, &user))        .await        .map_err(|e| {            eprintln!("{}", e);            HttpResponse::InternalServerError().finish()        })?;    Ok(HttpResponse::Ok().json(user))}

I can receive several connections by repeated calls of pool.get(), but that inefficient to open a new SQL connection when one connection is enough.

So, how to deal with this?


Viewing all articles
Browse latest Browse all 12

Latest Images

Trending Articles





Latest Images