Struct sea_orm::entity::prelude::Select

source ·
pub struct Select<E>where
    E: EntityTrait,
{ /* private fields */ }
Expand description

Defines a structure to perform select operations

Implementations§

Perform a Select operation on a Model using a Statement

Return a Selector from Self that wraps a SelectModel

Examples found in repository?
src/executor/paginator.rs (line 283)
282
283
284
    fn paginate(self, db: &'db C, page_size: u64) -> Paginator<'db, C, Self::Selector> {
        self.into_model().paginate(db, page_size)
    }
More examples
Hide additional examples
src/executor/select.rs (line 261)
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
    pub async fn one<'a, C>(self, db: &C) -> Result<Option<E::Model>, DbErr>
    where
        C: ConnectionTrait,
    {
        self.into_model().one(db).await
    }

    /// Get all Models from the SELECT query
    pub async fn all<'a, C>(self, db: &C) -> Result<Vec<E::Model>, DbErr>
    where
        C: ConnectionTrait,
    {
        self.into_model().all(db).await
    }

    /// Stream the results of a SELECT operation on a Model
    pub async fn stream<'a: 'b, 'b, C>(
        self,
        db: &'a C,
    ) -> Result<impl Stream<Item = Result<E::Model, DbErr>> + 'b + Send, DbErr>
    where
        C: ConnectionTrait + StreamTrait + Send,
    {
        self.into_model().stream(db).await
    }

Get a selectable Model as a JsonValue for SQL JSON operations

use sea_orm::{entity::*, query::*, tests_cfg::cake, DeriveColumn, EnumIter};

#[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
enum QueryAs {
    CakeName,
}

let res: Vec<String> = cake::Entity::find()
    .select_only()
    .column_as(cake::Column::Name, QueryAs::CakeName)
    .into_values::<_, QueryAs>()
    .all(&db)
    .await?;

assert_eq!(
    res,
    vec!["Chocolate Forest".to_owned(), "New York Cheese".to_owned()]
);

assert_eq!(
    db.into_transaction_log(),
    vec![Transaction::from_sql_and_values(
        DbBackend::Postgres,
        r#"SELECT "cake"."name" AS "cake_name" FROM "cake""#,
        vec![]
    )]
);
use sea_orm::{entity::*, query::*, tests_cfg::cake, DeriveColumn, EnumIter};

#[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
enum QueryAs {
    CakeName,
    NumOfCakes,
}

let res: Vec<(String, i64)> = cake::Entity::find()
    .select_only()
    .column_as(cake::Column::Name, QueryAs::CakeName)
    .column_as(cake::Column::Id.count(), QueryAs::NumOfCakes)
    .group_by(cake::Column::Name)
    .into_values::<_, QueryAs>()
    .all(&db)
    .await?;

assert_eq!(res, vec![("Chocolate Forest".to_owned(), 2i64)]);

assert_eq!(
    db.into_transaction_log(),
    vec![Transaction::from_sql_and_values(
        DbBackend::Postgres,
        vec![
            r#"SELECT "cake"."name" AS "cake_name", COUNT("cake"."id") AS "num_of_cakes""#,
            r#"FROM "cake" GROUP BY "cake"."name""#,
        ]
        .join(" ")
        .as_str(),
        vec![]
    )]
);

Get one Model from the SELECT query

Examples found in repository?
src/executor/insert.rs (line 203)
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
async fn exec_insert_with_returning<A, C>(
    primary_key: Option<ValueTuple>,
    mut insert_statement: InsertStatement,
    db: &C,
) -> Result<<A::Entity as EntityTrait>::Model, DbErr>
where
    <A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
    C: ConnectionTrait,
    A: ActiveModelTrait,
{
    let db_backend = db.get_database_backend();
    let found = match db.support_returning() {
        true => {
            let returning = Query::returning().exprs(
                <A::Entity as EntityTrait>::Column::iter()
                    .map(|c| cast_enum_as_text(Expr::col(c), &c)),
            );
            insert_statement.returning(returning);
            SelectorRaw::<SelectModel<<A::Entity as EntityTrait>::Model>>::from_statement(
                db_backend.build(&insert_statement),
            )
            .one(db)
            .await?
        }
        false => {
            let insert_res =
                exec_insert::<A, _>(primary_key, db_backend.build(&insert_statement), db).await?;
            <A::Entity as EntityTrait>::find_by_id(insert_res.last_insert_id)
                .one(db)
                .await?
        }
    };
    match found {
        Some(model) => Ok(model),
        None => Err(DbErr::RecordNotFound(
            "Failed to find inserted item".to_owned(),
        )),
    }
}
More examples
Hide additional examples
src/executor/update.rs (line 122)
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
async fn exec_update_and_return_updated<A, C>(
    mut query: UpdateStatement,
    model: A,
    db: &C,
) -> Result<<A::Entity as EntityTrait>::Model, DbErr>
where
    A: ActiveModelTrait,
    C: ConnectionTrait,
{
    match db.support_returning() {
        true => {
            let returning = Query::returning().exprs(
                <A::Entity as EntityTrait>::Column::iter()
                    .map(|c| cast_enum_as_text(Expr::col(c), &c)),
            );
            query.returning(returning);
            let db_backend = db.get_database_backend();
            let found: Option<<A::Entity as EntityTrait>::Model> =
                SelectorRaw::<SelectModel<<A::Entity as EntityTrait>::Model>>::from_statement(
                    db_backend.build(&query),
                )
                .one(db)
                .await?;
            // If we got `None` then we are updating a row that does not exist.
            match found {
                Some(model) => Ok(model),
                None => Err(DbErr::RecordNotFound(
                    "None of the database rows are affected".to_owned(),
                )),
            }
        }
        false => {
            // If we updating a row that does not exist then an error will be thrown here.
            Updater::new(query).check_record_exists().exec(db).await?;
            let primary_key_value = match model.get_primary_key_value() {
                Some(val) => FromValueTuple::from_value_tuple(val),
                None => return Err(DbErr::UpdateGetPrimaryKey),
            };
            let found = <A::Entity as EntityTrait>::find_by_id(primary_key_value)
                .one(db)
                .await?;
            // If we cannot select the updated row from db by the cached primary key
            match found {
                Some(model) => Ok(model),
                None => Err(DbErr::RecordNotFound(
                    "Failed to find updated item".to_owned(),
                )),
            }
        }
    }
}

Get all Models from the SELECT query

Stream the results of a SELECT operation on a Model

Selects and Entity and returns it together with the Entity from Self

Examples found in repository?
src/query/join.rs (line 53)
48
49
50
51
52
53
54
    pub fn find_also_related<R>(self, r: R) -> SelectTwo<E, R>
    where
        R: EntityTrait,
        E: Related<R>,
    {
        self.left_join(r).select_also(r)
    }

Makes a SELECT operation in conjunction to another relation

Examples found in repository?
src/query/join.rs (line 62)
57
58
59
60
61
62
63
    pub fn find_with_related<R>(self, r: R) -> SelectTwoMany<E, R>
    where
        R: EntityTrait,
        E: Related<R>,
    {
        self.left_join(r).select_with(r)
    }

Left Join with a Related Entity.

Examples found in repository?
src/query/join.rs (line 53)
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
    pub fn find_also_related<R>(self, r: R) -> SelectTwo<E, R>
    where
        R: EntityTrait,
        E: Related<R>,
    {
        self.left_join(r).select_also(r)
    }

    /// Left Join with a Related Entity and select the related Entity as a `Vec`
    pub fn find_with_related<R>(self, r: R) -> SelectTwoMany<E, R>
    where
        R: EntityTrait,
        E: Related<R>,
    {
        self.left_join(r).select_with(r)
    }

Right Join with a Related Entity.

Inner Join with a Related Entity.

Join with an Entity Related to me.

Left Join with a Related Entity and select both Entity.

Left Join with a Related Entity and select the related Entity as a Vec

Left Join with a Linked Entity and select both Entity.

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Select operation
Convert current type into a cursor
Formats the value using the given formatter. Read more
Select operation
Paginate the result of a select operation.
Perform a count on the paginated results
Add the query to perform a FILTER on
Add an AND WHERE expression Read more
Apply a where condition using the model’s primary key
Perform a check to determine table belongs to a Model through it’s name alias
Add the query to perform an ORDER BY operation
Add an order_by expression Read more
Add an order_by expression (ascending) Read more
Add an order_by expression (descending) Read more
Add the select SQL statement
Clear the selection list
Add a select column Read more
Add a select column with alias Read more
Select columns Read more
Add an offset expression Read more
Add a limit expression Read more
Add a group by column Read more
Add an AND HAVING expression Read more
Add a DISTINCT expression Read more
Add a DISTINCT ON expression NOTE: this function is only supported by sqlx-postgres Read more
Join via RelationDef.
Join via RelationDef but in reverse direction. Assume when there exist a relation A to B. You can reverse join B from A.
Join via RelationDef with table alias.
Join via RelationDef with table alias but in reverse direction. Assume when there exist a relation A to B. You can reverse join B from A.
Select lock
Select lock shared
Select lock exclusive
Constrain the QueryStatement to QueryStatementBuilder trait
Get a mutable ref to the query builder
Get an immutable ref to the query builder
Take ownership of the query builder
Build the query as Statement

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more