Search code examples
asynchronousrustrust-tokiorust-sqlx

How to implement a trait on any type that implements PgExecutor?


I have my own trait to extend the functionality that the PgExecutor trait provides.

I want to implement these trait on anything that implements PgExecutor but I'm honestly having a hard time.

#[async_trait]
impl<'a, T> PgExecutorExt for T
    where T: PgExecutor<'a> + Sync
 {
    async fn my_read_method(&self) -> anyhow::Result<()> {
        sqlx::query_as!(...)
        .fetch_one(self)
        .await?;

        Ok(())
    }
}

But I'm getting the following error:

the trait bound `&T: Executor<'_>` is not satisfied
the trait `Executor<'_>` is not implemented for `&T` 

On the .fetch_one(self) call

anyone has any clue on what is going on?? Thank you!


Solution

  • The Executor::fetch_one() function takes self, not &self. You need to change &self to self in your trait definition and this implementation, and that should fix the issue.