From 1928f238935f6b3d1920838b80236199291b3b30 Mon Sep 17 00:00:00 2001 From: Taylor Beever Date: Thu, 15 Aug 2024 09:09:51 -0600 Subject: [PATCH] feat: Add .apply_if to SelectStatement (#800) * feat: Add .apply_if to SelectStatement * fix: Satisfy cargo fmt in doctest --- src/query/select.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/query/select.rs b/src/query/select.rs index dd39862a..debd0807 100644 --- a/src/query/select.rs +++ b/src/query/select.rs @@ -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(&mut self, val: Option, 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