0

I'm using SQLx to define a trait that is to be implemented on PgPool, MySqlPool, etc. and looks something like this:

#[async_trait]
trait MyTrait {
    const QUERY: &'static str;

    fn fetch(&self) -> Option<Self> {
        sqlx::query(Self::QUERY)
            .fetch_one(self)
            .await
            .map(|row| row.get(0))
            .ok()
    }
}

#[async_trait]
impl MyTrait for sqlx::PgPool {
    const QUERY: &'static str = "SELECT value FROM table WHERE id = 10";
}

This does not compile with:

error[E0277]: the trait bound `&Self: sqlx::Executor<'_>` is not satisfied
   --> service/src/lib.rs:265:24
    |
265 |             .fetch_one(self)
    |              --------- ^^^^ the trait `sqlx::Executor<'_>` is not implemented for `&Self`
    |              |
    |              required by a bound introduced by this call
    |
note: required by a bound in `sqlx::query::Query::<'q, DB, A>::fetch_one`

I've tried adding where Self: sqlx::Executor<'..., Datbase = DB> and numerous variations of it but to no avail unfortunately.

I'm currently trying something like MyTrait<'p, DB: sqlx::Database> where &'p Self: sqlx::Executor<'p, Database = DB>, Self: 'p with implementation impl MyTrait<'_, sqlx::Postgres> for PgPool but this gives the error type mismatch resolving `<&Self as sqlx::Executor<'_>>::Database == Postgres`

If anybody could tell me how I need to modify my code in order for it to compile I would really appreciate it, thank you.

bmoxb
  • 33
  • 3
  • Try taking a look at my answer to [this question](https://stackoverflow.com/a/70573732/4307644) for a hint – MeetTitan Apr 21 '22 at 17:16
  • @MeetTitan Thank you, I'm now a bit closer with `Trait where for<'c> &'c Self: sqlx::Executor<'c, Database = DB>` but this still errors with ``type mismatch resolving `<&Self as sqlx::Executor<'_>>::Database == Postgres` `` - struggling to make things generic over the database type. – bmoxb Apr 21 '22 at 18:04
  • How are you calling your shown code? – MeetTitan Apr 22 '22 at 17:45

0 Answers0