sfackler / rust-postgres

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

Why do transactions borrow the connections mutably? #776

Closed ghost closed 3 years ago

ghost commented 3 years ago

This is the signature of Client::build_transaction method:

    pub fn build_transaction(&mut self) -> TransactionBuilder<'_> {
        TransactionBuilder::new(self)
    }

Can you describe why this method takes a mutable reference to the client? Is it to make the borrow checker enforce that only one transaction is active, and that the client cannot be used while a transaction is active? Are there any other reasons which require a transaction to hold a mutable reference?

Also, I wanted to know if I'm correct in assuming that a tokio-postgres client is thread safe and can be used from multiple threads without any additional synchronization constructs?

sfackler commented 3 years ago

The entire connection moves into "transaction mode" when a transaction is started, and so the mutable borrow is used to prevent other uses at the same time in ways that could end up being broken or confusing.

If you are not in a transaction, you can use the tokio-postgres client concurrently in multiple threads, though unless you're absolutely sure you only ever need to make single one-off queries you would probably be better off using a connection pool.

ghost commented 3 years ago

Thanks