diff --git a/src/query/traits.rs b/src/query/traits.rs index cfc35350..2dd30d56 100644 --- a/src/query/traits.rs +++ b/src/query/traits.rs @@ -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` 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(self, val: Option, if_some: F) -> Self + where + Self: Sized, + F: FnOnce(Self, T) -> Self, + { + if let Some(val) = val { + if_some(self, val) + } else { + self + } + } }