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), |query, v| { query.filter(cake::Column::Id.eq(v)) })
32 /// .apply_if(Some(100), QuerySelect::limit)
33 /// .apply_if(None, QuerySelect::offset::<Option<u64>>) // no-op
34 /// .build(DbBackend::Postgres)
35 /// .to_string(),
36 /// r#"SELECT "cake"."id", "cake"."name" FROM "cake" WHERE "cake"."id" = 3 LIMIT 100"#
37 /// );
38 /// ```
39 fn apply_if<T, F>(self, val: Option<T>, if_some: F) -> Self
40 where
41 Self: Sized,
42 F: FnOnce(Self, T) -> Self,
43 {
44 if let Some(val) = val {
45 if_some(self, val)
46 } else {
47 self
48 }
49 }
50}