How do I abstract a database a database query to a function? #2581
Answered
by
frenetisch-applaudierend
Hugo-Persson
asked this question in
Questions
-
I am having some problems using sqlx::postgres with rocket.rs. I want to pass my database connection to a different function to perform a query and return the result parsed. How do I do this? This code work for my function but the problem is that I am moving my Connection from my first function which I do not want: pub async fn isin_exists(isin: &String, mut db: Connection<GhostfolioDB>) -> bool {
let query = r#"SELECT id FROM "SymbolProfile" WHERE isin = '?' LIMIT 1;"#;
let res = sqlx::query(query).bind(isin).fetch_one(&mut *db).await;
res.is_ok()
}
#[post("/init", data = "<data>")]
async fn init_form(
mut db: Connection<GhostfolioDB>,
mut data: Form<InitTickersFormData<'_>>,
) -> Template {
let tickers = get_tickers_from_csv(data.csv.path().unwrap(), &data.isin_column);
let hits_async = tickers[1..3].iter().map(search_avanza);
let mut hits_result: Vec<Hit> = vec![];
for hit in hits_async {
let res = hit.await;
match res {
Ok((isin, hit)) => {
if !isin_exists(isin, db).await {
hits_result.push(hit);
}
}
Err(err) => println!("Error: {}", err),
}
}
println!("{:#?}", tickers);
info!("Result from avanza is: {:#?}", hits_result);
Template::render(
"select-tickers",
context! {
hits: hits_result
},
)
} |
Beta Was this translation helpful? Give feedback.
Answered by
frenetisch-applaudierend
Aug 4, 2023
Replies: 1 comment
-
I'm not entirely sure I understood your question correctly, but if you don't want to move the connection, why not borrowing? You only need a &mut in
|
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
SergioBenitez
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm not entirely sure I understood your question correctly, but if you don't want to move the connection, why not borrowing? You only need a &mut in
isin_exists
so no need to move the value at all: