sqlx icon indicating copy to clipboard operation
sqlx copied to clipboard

How to create "repository" generic over the database?

Open gzp79 opened this issue 3 years ago • 1 comments

I have a repository with a few create/read/update/get methods using transactions and pool. Nothing special. Now I'm trying to make it generic over the database to support both sqlite and postgresql.

struct Repo <DB:Database>{pool: Pool<DB>}
impl<DB> Repo<DB> {
  pub  async fn create ...
  pub async fn delete ...
}

It works fine as long as it is not generic and the repo works fine for either sqlite or postgres. But to make it generic I've failed. I've tried to set the required where clause something like this (and a lot other permutation).

where
    DB: Database,
    for<'a> bool: Encode<'a, DB> + Type<DB>,
    for<'a> bool: Decode<'a, DB> + Type<DB>,
    for<'a> i32: Encode<'a, DB> + Type<DB>,
    for<'a> i32: Decode<'a, DB> + Type<DB>,
    //for<'a> u32: Encode<'a, DB> + Type<DB>,
    for<'a> String: Encode<'a, DB> + Type<DB>,
    for<'a> String: Decode<'a, DB> + Type<DB>,
    for<'a> Option<String>: Encode<'a, DB> + Type<DB>,
    for<'a> Option<String>: Decode<'a, DB> + Type<DB>,
    for<'a> &'a str: Encode<'a, DB> + Type<DB>,
    for<'a> &'a str: Decode<'a, DB> + Type<DB>,
    for<'a> Option<&'a str>: Encode<'a, DB> + Type<DB>,
    for<'a> Option<&'a str>: Decode<'a, DB> + Type<DB>,
    for<'a> DateTime<Utc>: Encode<'a, DB> + Type<DB>,
    for<'a> DateTime<Utc>: Decode<'a, DB> + Type<DB>,
    for<'a> usize: ColumnIndex<DB::Row>,
    for<'a> <DB as HasArguments<'a>>::Arguments: 'a + IntoArguments<'a, DB>,
    for<'a, 'c> &'a mut DB::Connection: 'a + Executor<'c, Database = DB>,
    for<'a, 'c> &'a mut Transaction<'a, DB>: 'a + Executor<'c, Database = DB>,
    DB::Connection: Migrate,

But failed on the Executor part.

I know there is the Any database, but unfortunately due to it's long standing bug (https://github.com/launchbadge/sqlx/issues/1407) it is not an option for me as I found no workaround for it yet. (Also as I don't have the deep understanding of sqlx I've also failed PR/fix it the crate)

gzp79 avatar Feb 04 '22 13:02 gzp79

Any update on this issue ?

gzp79 avatar Jul 12 '22 08:07 gzp79