Skip to content

Commit

Permalink
QueryTrait::maybe: a general purpose query customizer (#1415)
Browse files Browse the repository at this point in the history
* Added `QueryTrait::maybe`

* Make the API better

* Docs

* Update src/query/traits.rs

Co-authored-by: Chris Tsang <chris.2y3@outlook.com>
  • Loading branch information
billy1624 and tyt2y3 authored Jan 26, 2023
1 parent 3b57b7a commit 1c43508
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/query/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,35 @@ pub trait QueryTrait {
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
}
}
}

0 comments on commit 1c43508

Please sign in to comment.