Implementing a custom predicate? #2905
-
In a case where a certain table has more than one identifying column (e.g. a user with id and unique email), I wanted to try to implement a custom predicate to filter for either one of the two. For example, I'd love to be able to do something like this: use crate::schema::users;
// Queryable, etc.
pub struct User {
pub id: i32, // In practice, this is a id newtype
pub email: String,
...
}
pub enum UserIdentifier<'a> {
Id(i32),
Email(&'a str),
}
fn read(conn: &db::Connection, id: UserIdentifier) -> QueryResult<Self> {
users::table.filter(id).first::<User>(conn)
} rather than having to differentiate between But I'm not sure what the types on that impl would look like. There doesn't appear to be a If feels possible, but maybe this is just one of those type shenanigans that isn't? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I would suggest to either have an method on |
Beta Was this translation helpful? Give feedback.
I would suggest to either have an method on
UserIdentifier
which converts that type into aBox<dyn BoxableExpression<…, SqlType = Bool>>
or to directly implementAsExpression<Bool>
forUserIdentifier
(Note: You need to manually implement this. The derive will not work for this case). Both allow reusing all existingFilterDsl
implementations + allow to mix this with other predicates.