sea_orm/query/traits.rs
1use crate::{DbBackend, Statement, StatementBuilder};
2
3/// A Trait for any type performing queries on a Model or ActiveModel
4pub trait QueryTrait {
5 /// Constrain the QueryStatement to [StatementBuilder] trait
6 type QueryStatement: StatementBuilder;
7
8 /// Get a mutable ref to the query builder
9 fn query(&mut self) -> &mut Self::QueryStatement;
10
11 /// Get an immutable ref to the query builder
12 fn as_query(&self) -> &Self::QueryStatement;
13
14 /// Take ownership of the query builder
15 fn into_query(self) -> Self::QueryStatement;
16
17 /// Build the query as [`Statement`]
18 fn build(&self, db_backend: DbBackend) -> Statement {
19 StatementBuilder::build(self.as_query(), &db_backend)
20 }
21
22 /// Apply an operation on the [QueryTrait::QueryStatement] if the given `Option<T>` is `Some(_)`
23 ///
24 /// # Example
25 ///
26 /// ```
27 /// use sea_orm::{DbBackend, entity::*, query::*, tests_cfg::cake};
28 ///
29 /// assert_eq!(
30 /// cake::Entity::find()
31 /// .apply_if(Some(3), |mut query, v| {
32 /// query.filter(cake::Column::Id.eq(v))
33 /// })
34 /// .apply_if(Some(100), QuerySelect::limit)
35 /// .apply_if(None, QuerySelect::offset::<Option<u64>>) // no-op
36 /// .build(DbBackend::Postgres)
37 /// .to_string(),
38 /// r#"SELECT "cake"."id", "cake"."name" FROM "cake" WHERE "cake"."id" = 3 LIMIT 100"#
39 /// );
40 /// ```
41 fn apply_if<T, F>(self, val: Option<T>, if_some: F) -> Self
42 where
43 Self: Sized,
44 F: FnOnce(Self, T) -> Self,
45 {
46 if let Some(val) = val {
47 if_some(self, val)
48 } else {
49 self
50 }
51 }
52}