Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

QueryTrait::maybe: a general purpose query customizer #1415

Merged
merged 4 commits into from
Jan 26, 2023
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 a operation on the [QueryTrait::QueryStatement] if the given `Option<T>` is `Some(_)`
tyt2y3 marked this conversation as resolved.
Show resolved Hide resolved
///
/// # 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
}
}
}