I am using Rust with sqlx and postgres to build a REST API. I am trying to build a Database
struct which has a generic connection param in it.
struct Database<T>
where
T: Sync + Send,
for<'a> &'a T: sqlx::Executor<'a, Database = Postgres>,
{
conn: T
}
T
would be owned by the struct, and &T
is expected to implement Executor
trait.
I am able to use Pool<Postgres>
as T
, since &Pool<Postgres>
implements the Executor
.
What I want is (and this is the reason I made the conn
a generic type) to be able to use Transaction<Postgres>
as T
. But the problem is that &Transaction<Postgres>
does not implement the Executor
trait, but &mut Transaction<Postgres>
does.
The reason I want to do this is there are CRUD functions that I want to be able to use with both a transaction and a pool connection. And I don't want to write duplicate code. How can I achieve this?