sfackler / rust-postgres

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

Make `tokio_postgres::Client` implement `Clone` #1031

Closed xfbs closed 1 year ago

xfbs commented 1 year ago

Hey,

Just out of curiosity: should the Client potentially implement Clone?

sfackler commented 1 year ago

Connections are stateful, and can't be used concurrently.

xfbs commented 1 year ago

Here's the definition of Client:

/// An asynchronous PostgreSQL client.
///
/// The client is one half of what is returned when a connection is established. Users interact with the database
/// through this client object.
pub struct Client {
    inner: Arc<InnerClient>,
    #[cfg(feature = "runtime")]
    socket_config: Option<SocketConfig>,
    ssl_mode: SslMode,
    process_id: i32,
    secret_key: i32,
}

The actual client is already wrapped in an Arc and thus be cheaply cloned. Both SslMode and SocketConfig implement Clone already. All of the methods take only a &self reference to the client.

I understand that the Connection is stateful, but the Client itself only performs message-passing.

So by this:

Connections are stateful, and can't be used concurrently.

You mean that the underlying connection to Postgres is stateful, and so even though we could cheaply clone Clients, they are not fully independent clients as the cloning would suggest, but they share an underlying connection (and as such, connection-specific state on the Postgres side)?

So, if I am aware that there is connection-specific state, but I am okay with that, I should simply use an Arc<Client> in my application?

sfackler commented 1 year ago

You mean that the underlying connection to Postgres is stateful, and so even though we could cheaply clone Clients, they are not fully independent clients as the cloning would suggest, but they share an underlying connection (and as such, connection-specific state on the Postgres side)?

Yes

So, if I am aware that there is connection-specific state, but I am okay with that, I should simply use an Arc<Client> in my application?

I would strongly recommend against that, but it is a thing you could do.