How can I have the same sqlx transaction through multiple functions?

215 views Asked by At

I have the following simple scenario for a REST API and I'm not sure how should I do it idiomatically in Rust. So basically there's a get˙function that returns a variable type X from the database. This get function currently receives a sqlx::MysqlPool, creates a transaction, runs the queries to get the data, commits, returns it, done. So far so good.

I have multiple endpoints, but for this example let's say there's an update function, which should update the record in the database and return the object afterwards.

My problem is that I'm not sure how I can do this properly.

  1. I could just do the update with one transaction, and reuse the get function afterwards, but that would be two separate transactions and so it's theoretically possible that between those transactions an other client updates the same record as well. Also it doesn't seem optimal.

  2. Somehow share the same transaction between those functions, but in that case I would need to start the transaction outside of any of these functions, which somehow doesn't feel right.

  3. Simply duplicate most of the get function's code in the update function, but that doesn't seem to be a good idea, specially if I need to do it in 4-5 functions.

How do people get around this issue?

0

There are 0 answers