A Trait for any type performing queries on a Model or ActiveModel
| 3 | |
| 4 | /// A Trait for any type performing queries on a Model or ActiveModel |
| 5 | pub 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 |
| 60 | pub trait SelectColumns { |