#SOLVED: Constrain deeply nested types within traits

2 messages · Page 1 of 1 (latest)

polar gyro
#

Context: I'm looking to implement a SeaOrm-backed view repository for cqrs-es so I can use SQL queries on events rather than storing id->json pairs.

I think this one gets pretty complicated. I have implemented a struct which has a type parameter that is constrained to two traits. See the following code:


pub struct SeaOrmViewRepository<V, A> {
    connection: DatabaseConnection,
    _phantom: PhantomData<(V, A)>,
}

#[async_trait]
impl<V, A> ViewRepository<V, A> for SeaOrmViewRepository<V, A>
where
    A: Aggregate + ModelTrait,
    V: View<A>,
{
    /// code here ...
}

this compiles very well. I found that it doesn't integrate with cqrs-es so much. ModelTrait has a deeply nested type at A::Entity::PrimaryKey::ValueType that I need to make sure it's a type that can be created from an &str. I tried the following, and I'm getting compiler errors:

impl<V, A> ViewRepository<V, A> for SeaOrmViewRepository<V, A>
where
    A: Aggregate + ModelTrait<<<Entity as EntityTrait>::PrimaryKey as PrimaryKeyTrait>::ValueType = From<&str>>,
    V: View<A>,
{}``````
   |                                                                                         --------- ^ expected one of `(`, `,`, `::`, `:`, `<`, or `>`
   |                                                                                         |

Does anyone have any suggestions for how to make sure that ValueType can be constrained a type that implements From<&str>?

polar gyro
#

Okay, so I was on the right track. Turns out the answer is pretty simple. The nested PrimaryKey type already implemented FromStr, so that bound didn't need to exist. However, for error reporting, I did need to ensure that the error returned from FromStr could be converted into a dyn Error. This is what the syntax looks like:

#[async_trait]
impl<V, A> ViewRepository<V, A> for SeaOrmViewRepository<V, A>
where
    A: Aggregate + ModelTrait,
    V: View<A>,
    <<<A::Entity as EntityTrait>::PrimaryKey as PrimaryKeyToColumn>::Column as FromStr>::Err:
        Into<Box<dyn Error + Send + Sync>>,
{}