sfackler / rust-postgres

Native PostgreSQL driver for the Rust programming language
Apache License 2.0
3.43k stars 436 forks source link

Client mutable in transaction in tokio-postgres #1032

Closed AnthonyPoncet closed 1 year ago

AnthonyPoncet commented 1 year ago

Hello,

I face an issue with the fact that the reference of the client in the Transaction struct in tokio-postgres crate is mutable. Looking at the code, I cannot to spot why, does someone have an idea ?

To give more context on the error, I have the client which is shared among several thread (stored in an Arc). To make it mutable, the only solution I can see is to put it in a Arc<Mutex>. Doing so bring another issue, calling await will make the thread with the mutex available and then can create deadlock. I could use try_lock but it bring other issues.

If the mutable client is not needed, would you be ok to make it non mutable?

sfackler commented 1 year ago

It is mutable to avoid exactly this situation - transactions modify the state of the connection, and you can't run multiple connections in separate thread on one connection concurrently.

You should use a connection pool and avoid sharing connections concurrently.

AnthonyPoncet commented 1 year ago

Thanks for your answer.

By modifying the connection, is it the fact it start a begin transaction on the connection ?

I am right thinking you meant running a transaction on the connection, prevent running another query or transaction on the same connection (could be different thread or the same with async) ? But running multiple simple queries on the same connection on seperate thread is ok as a query does not modify the client/connection?

sfackler commented 1 year ago

Starting a transaction switches the entire connection into transaction mode. It does not prevent running another query on the same connection, it makes that query part of the transaction.

AnthonyPoncet commented 1 year ago

Thanks again for all, I will close this ticket