sea_orm/query/traits.rs
1use crate::{ColumnAsExpr, ColumnTrait, DbBackend, IntoIdentity, QuerySelect, Statement};
2use sea_query::QueryStatementBuilder;
3
4/// A Trait for any type performing queries on a Model or ActiveModel
5pub trait QueryTrait {
6 /// Constrain the QueryStatement to [QueryStatementBuilder] trait
7 type QueryStatement: QueryStatementBuilder;
8
9 /// Get a mutable ref to the query builder
10 fn query(&mut self) -> &mut Self::QueryStatement;
11
12 /// Get an immutable ref to the query builder
13 fn as_query(&self) -> &Self::QueryStatement;
14
15 /// Take ownership of the query builder
16 fn into_query(self) -> Self::QueryStatement;
17
18 /// Build the query as [`Statement`]
19 fn build(&self, db_backend: DbBackend) -> Statement {
20 let query_builder = db_backend.get_query_builder();
21 Statement::from_string_values_tuple(
22 db_backend,
23 self.as_query().build_any(query_builder.as_ref()),
24 )
25 }
26
27 /// Apply an operation on the [QueryTrait::QueryStatement] if the given `Option<T>` is `Some(_)`
28 ///
29 /// # Example
30 ///
31 /// ```
32 /// use sea_orm::{entity::*, query::*, tests_cfg::cake, DbBackend};
33 ///
34 /// assert_eq!(
35 /// cake::Entity::find()
36 /// .apply_if(Some(3), |mut query, v| {
37 /// query.filter(cake::Column::Id.eq(v))
38 /// })
39 /// .apply_if(Some(100), QuerySelect::limit)
40 /// .apply_if(None, QuerySelect::offset::<Option<u64>>) // no-op
41 /// .build(DbBackend::Postgres)
42 /// .to_string(),
43 /// r#"SELECT "cake"."id", "cake"."name" FROM "cake" WHERE "cake"."id" = 3 LIMIT 100"#
44 /// );
45 /// ```
46 fn apply_if<T, F>(self, val: Option<T>, if_some: F) -> Self
47 where
48 Self: Sized,
49 F: FnOnce(Self, T) -> Self,
50 {
51 if let Some(val) = val {
52 if_some(self, val)
53 } else {
54 self
55 }
56 }
57}
58
59/// Select specific column for partial model queries
60pub trait SelectColumns {
61 /// Add a select column
62 ///
63 /// For more detail, please visit [QuerySelect::column]
64 fn select_column<C: ColumnTrait>(self, col: C) -> Self;
65
66 /// Add a select column with alias
67 ///
68 /// For more detail, please visit [QuerySelect::column_as]
69 fn select_column_as<C, I>(self, col: C, alias: I) -> Self
70 where
71 C: ColumnAsExpr,
72 I: IntoIdentity;
73}
74
75impl<S> SelectColumns for S
76where
77 S: QuerySelect,
78{
79 fn select_column<C: ColumnTrait>(self, col: C) -> Self {
80 QuerySelect::column(self, col)
81 }
82
83 fn select_column_as<C, I>(self, col: C, alias: I) -> Self
84 where
85 C: ColumnAsExpr,
86 I: IntoIdentity,
87 {
88 QuerySelect::column_as(self, col, alias)
89 }
90}