sfackler / rust-postgres

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

the trait `tokio_postgres::generic_client::GenericClient` cannot be made into an object #572

Closed jsandler18 closed 4 years ago

jsandler18 commented 4 years ago

Hello, I have this simple function:

pub async fn get_user_by_username(client: & dyn GenericClient, username: &str) -> Result<Option<Self>, Error> {
        client.query_opt("SELECT * FROM users WHERE username = $1", &[username])
            .await?
            .try_into()
    }

And I am getting this error:

 the trait `tokio_postgres::generic_client::GenericClient` cannot be made into an object
  --> backend/src/handlers/authn.rs:53:43
   |
53 |     let row = Users::get_user_by_username(&conn, &login.username).await
   |                                           ^^^^^ the trait `tokio_postgres::generic_client::GenericClient` cannot be made into an object
   |
   = note: method `execute` has generic type parameters
   = note: method `execute_raw` has generic type parameters
   = note: method `query` has generic type parameters
   = note: method `query_one` has generic type parameters
   = note: method `query_opt` has generic type parameters
   = note: method `query_raw` has generic type parameters
   = note: required because of the requirements on the impl of `std::ops::CoerceUnsized<&dyn tokio_postgres::generic_client::GenericClient>` for `&bb8::PooledConnection<'_, bb8_postgres::PostgresConnectionManager<tokio_postgres::tls::NoTls>>`
   = note: required by cast to type `&dyn tokio_postgres::generic_client::GenericClient`

Any idea what is wrong or how I can fix it? The Rust Compiler Error Index seems to say that it is on the trait owner to fix it? Does this mean I am SOL?

sfackler commented 4 years ago

You can't use GenericClient as a trait object. You can instead use it as a type parameter:

pub async fn get_user_by_username<T>(client: &T, username: &str) -> Result<Option<Self>, Error>
where
    T: GenericClient,
{
    ...
}