Skip to content

Commit

Permalink
feat: Add .apply_if to SelectStatement (#800)
Browse files Browse the repository at this point in the history
* feat: Add .apply_if to SelectStatement

* fix: Satisfy cargo fmt in doctest
  • Loading branch information
theelderbeever authored Aug 15, 2024
1 parent 5292ca3 commit 1928f23
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/query/select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,37 @@ impl SelectStatement {
self
}

/// A shorthand to express if ... else ... when constructing the select statement.
///
/// # Examples
///
/// ```
/// use sea_query::{tests_cfg::*, *};
///
/// let query = Query::select()
/// .column(Char::Character)
/// .from(Char::Table)
/// .apply_if(Some(5), |q, v| {
/// q.and_where(Expr::col(Char::FontId).eq(v));
/// })
/// .to_owned();
///
/// assert_eq!(
/// query.to_string(MysqlQueryBuilder),
/// r#"SELECT `character` FROM `character` WHERE `font_id` = 5"#
/// );
/// ```
pub fn apply_if<T, F>(&mut self, val: Option<T>, if_some: F) -> &mut Self
where
Self: Sized,
F: FnOnce(&mut Self, T),
{
if let Some(val) = val {
if_some(self, val);
}
self
}

/// Construct part of the select statement in another function.
///
/// # Examples
Expand Down

0 comments on commit 1928f23

Please sign in to comment.