You can do more complex queries with nested and grouped and/or conditions and even re-use queries as conditions.
Define a flexible stucture
enum Condition {
bar(i32),
And(Vec<Condition>),
Or(Vec<Condition>),
}
Create boxed type
type Source = foo::dsl::foo;
type BoxedCondition = Box<dyn BoxableExpression<Source, Sqlite, SqlType = Bool>>;
Then can create a boxed condition
impl Condition {
fn to_boxed_condition(self) -> Option<BoxedCondition> {
Some(match self {
// Here we box the condition
Condition::bar(value) => Box::new(foo::dsl::bar.eq(value)),
// For and/or
Condition::And(conditions) => match create_filter(conditions, AndOr::And) {
Some(boxed_condition) => boxed_condition,
None => return None,
},
Condition::Or(conditions) => match create_filter(conditions, AndOr::Or) {
Some(boxed_condition) => boxed_condition,
None => return None,
},
})
}
}
And then apply boxed conditions for a Vec of conditions
fn create_filter(conditions: Vec<Condition>, and_or: AndOr) -> Option<BoxedCondition> {
conditions
.into_iter()
// Map into array of boxed conditions
.filter_map::<BoxedCondition, _>(Condition::to_boxed_condition)
// Reduce to a boxed_condition1.and(boxed_condition2).and(boxed_condition3)...
.fold(None, |boxed_conditions, boxed_condition| {
Some(match boxed_conditions {
Some(bc) => match and_or {
AndOr::And => Box::new(bc.and(boxed_condition)),
AndOr::Or => Box::new(bc.or(boxed_condition)),
},
None => boxed_condition,
})
})
}
Above can be used in a diesel-rs query:
// bar = 1 or (bar = 1 and bar = 0)
let condition = create_filter(
vec![Condition::Or(vec![
Condition::bar(1),
Condition::And(vec![Condition::bar(1), Condition::bar(0)]),
])],
AndOr::And,
)
.unwrap();
let result = foo::dsl::foo
.filter(condition)
.select(foo::dsl::id)
.load::<String>(&mut connection)
.unwrap()
)
// (bar = 1 or bar = 1) and bar = 0 === false
let condition = create_filter(
vec![Condition::And(vec![
Condition::Or(vec![Condition::bar(1), Condition::bar(1)]),
Condition::bar(0),
])],
AndOr::And,
)
.unwrap();
foo::dsl::foo
.filter(condition)
.select(foo::dsl::id)
.load::<String>(&mut connection)
.unwrap()
See full example here
For query re-use as inner statement you can go reference Inner Query section of the full by example tutorial