QueryTrait::maybe
: a general purpose query customizer (#1415)
* Added `QueryTrait::maybe` * Make the API better * Docs * Update src/query/traits.rs Co-authored-by: Chris Tsang <chris.2y3@outlook.com>
This commit is contained in:
parent
3b57b7ab8a
commit
1c43508b66
@ -23,4 +23,35 @@ pub trait QueryTrait {
|
|||||||
self.as_query().build_any(query_builder.as_ref()),
|
self.as_query().build_any(query_builder.as_ref()),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Apply an operation on the [QueryTrait::QueryStatement] if the given `Option<T>` is `Some(_)`
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use sea_orm::{entity::*, query::*, tests_cfg::cake, DbBackend};
|
||||||
|
///
|
||||||
|
/// assert_eq!(
|
||||||
|
/// cake::Entity::find()
|
||||||
|
/// .apply_if(Some(3), |mut query, v| {
|
||||||
|
/// query.filter(cake::Column::Id.eq(v))
|
||||||
|
/// })
|
||||||
|
/// .apply_if(Some(100), QuerySelect::limit)
|
||||||
|
/// .apply_if(None, QuerySelect::offset) // no-op
|
||||||
|
/// .build(DbBackend::Postgres)
|
||||||
|
/// .to_string(),
|
||||||
|
/// r#"SELECT "cake"."id", "cake"."name" FROM "cake" WHERE "cake"."id" = 3 LIMIT 100"#
|
||||||
|
/// );
|
||||||
|
/// ```
|
||||||
|
fn apply_if<T, F>(self, val: Option<T>, if_some: F) -> Self
|
||||||
|
where
|
||||||
|
Self: Sized,
|
||||||
|
F: FnOnce(Self, T) -> Self,
|
||||||
|
{
|
||||||
|
if let Some(val) = val {
|
||||||
|
if_some(self, val)
|
||||||
|
} else {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user