Skip to main content

sea_orm/query/
traits.rs

1use crate::{DbBackend, Statement, StatementBuilder};
2
3/// Common operations on a SeaORM query builder: borrow the underlying
4/// `sea_query` statement, build it into a backend-specific [`Statement`], or
5/// apply optional modifications via [`apply_if`](Self::apply_if).
6///
7/// Implemented by [`Select`](crate::Select), [`Insert`](crate::Insert),
8/// [`Update`](crate::Update), [`Delete`](crate::Delete), and their multi-row
9/// variants.
10pub trait QueryTrait {
11    /// The underlying `sea_query` statement type this builder produces.
12    type QueryStatement: StatementBuilder;
13
14    /// Mutable access to the underlying statement.
15    fn query(&mut self) -> &mut Self::QueryStatement;
16
17    /// Shared access to the underlying statement.
18    fn as_query(&self) -> &Self::QueryStatement;
19
20    /// Consume the builder and return the underlying statement.
21    fn into_query(self) -> Self::QueryStatement;
22
23    /// Render the query for `db_backend` as a [`Statement`] (SQL + bound
24    /// parameters). Useful for inspecting generated SQL in tests.
25    fn build(&self, db_backend: DbBackend) -> Statement {
26        StatementBuilder::build(self.as_query(), &db_backend)
27    }
28
29    /// Apply an operation on the [QueryTrait::QueryStatement] if the given `Option<T>` is `Some(_)`
30    ///
31    /// # Example
32    ///
33    /// ```
34    /// use sea_orm::{DbBackend, entity::*, query::*, tests_cfg::cake};
35    ///
36    /// assert_eq!(
37    ///     cake::Entity::find()
38    ///         .apply_if(Some(3), |query, v| { query.filter(cake::Column::Id.eq(v)) })
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}