Struct sea_orm::SelectorRaw
source · pub struct SelectorRaw<S>where
S: SelectorTrait,{ /* private fields */ }Expand description
Performs a raw SELECT operation on a model
Implementations§
source§impl<S> SelectorRaw<S>where
S: SelectorTrait,
impl<S> SelectorRaw<S>where
S: SelectorTrait,
sourcepub fn from_statement<M>(stmt: Statement) -> SelectorRaw<SelectModel<M>>where
M: FromQueryResult,
pub fn from_statement<M>(stmt: Statement) -> SelectorRaw<SelectModel<M>>where
M: FromQueryResult,
Select a custom Model from a raw SQL Statement.
Examples found in repository?
More examples
src/executor/insert.rs (lines 193-195)
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(),
)),
}
}src/executor/update.rs (lines 101-103)
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(),
)),
}
}
}
}sourcepub fn with_columns<T, C>(
stmt: Statement
) -> SelectorRaw<SelectGetableValue<T, C>>where
T: TryGetableMany,
C: IntoEnumIterator + Iden,
pub fn with_columns<T, C>(
stmt: Statement
) -> SelectorRaw<SelectGetableValue<T, C>>where
T: TryGetableMany,
C: IntoEnumIterator + Iden,
Create SelectorRaw from Statement and columns. Executing this SelectorRaw will
return a type T which implement TryGetableMany.
sourcepub fn into_model<M>(self) -> SelectorRaw<SelectModel<M>>where
M: FromQueryResult,
pub fn into_model<M>(self) -> SelectorRaw<SelectModel<M>>where
M: FromQueryResult,
use sea_orm::{entity::*, query::*, tests_cfg::cake, FromQueryResult};
#[derive(Debug, PartialEq, FromQueryResult)]
struct SelectResult {
name: String,
num_of_cakes: i32,
}
let res: Vec<SelectResult> = cake::Entity::find()
.from_raw_sql(Statement::from_sql_and_values(
DbBackend::Postgres,
r#"SELECT "cake"."name", count("cake"."id") AS "num_of_cakes" FROM "cake""#,
vec![],
))
.into_model::<SelectResult>()
.all(&db)
.await?;
assert_eq!(
res,
vec![
SelectResult {
name: "Chocolate Forest".to_owned(),
num_of_cakes: 1,
},
SelectResult {
name: "New York Cheese".to_owned(),
num_of_cakes: 1,
},
]
);
assert_eq!(
db.into_transaction_log(),
vec![Transaction::from_sql_and_values(
DbBackend::Postgres,
r#"SELECT "cake"."name", count("cake"."id") AS "num_of_cakes" FROM "cake""#,
vec![]
),]
);sourcepub fn into_json(self) -> SelectorRaw<SelectModel<JsonValue>>
pub fn into_json(self) -> SelectorRaw<SelectModel<JsonValue>>
use sea_orm::{entity::*, query::*, tests_cfg::cake};
let res: Vec<serde_json::Value> = cake::Entity::find().from_raw_sql(
Statement::from_sql_and_values(
DbBackend::Postgres, r#"SELECT "cake"."id", "cake"."name" FROM "cake""#, vec![]
)
)
.into_json()
.all(&db)
.await?;
assert_eq!(
res,
vec![
serde_json::json!({
"name": "Chocolate Forest",
"num_of_cakes": 1,
}),
serde_json::json!({
"name": "New York Cheese",
"num_of_cakes": 1,
}),
]
);
assert_eq!(
db.into_transaction_log(),
vec![
Transaction::from_sql_and_values(
DbBackend::Postgres, r#"SELECT "cake"."id", "cake"."name" FROM "cake""#, vec![]
),
]);sourcepub async fn one<'a, C>(self, db: &C) -> Result<Option<S::Item>, DbErr>where
C: ConnectionTrait,
pub async fn one<'a, C>(self, db: &C) -> Result<Option<S::Item>, DbErr>where
C: ConnectionTrait,
Get an item from the Select query
use sea_orm::{entity::*, query::*, tests_cfg::cake};
let _: Option<cake::Model> = cake::Entity::find()
.from_raw_sql(Statement::from_sql_and_values(
DbBackend::Postgres,
r#"SELECT "cake"."id", "cake"."name" FROM "cake" WHERE "id" = $1"#,
vec![1.into()],
))
.one(&db)
.await?;
assert_eq!(
db.into_transaction_log(),
vec![Transaction::from_sql_and_values(
DbBackend::Postgres,
r#"SELECT "cake"."id", "cake"."name" FROM "cake" WHERE "id" = $1"#,
vec![1.into()]
),]
);Examples found in repository?
More examples
src/executor/insert.rs (line 196)
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(),
)),
}
}src/executor/update.rs (line 104)
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(),
)),
}
}
}
}sourcepub async fn all<'a, C>(self, db: &C) -> Result<Vec<S::Item>, DbErr>where
C: ConnectionTrait,
pub async fn all<'a, C>(self, db: &C) -> Result<Vec<S::Item>, DbErr>where
C: ConnectionTrait,
Get all items from the Select query
use sea_orm::{entity::*, query::*, tests_cfg::cake};
let _: Vec<cake::Model> = cake::Entity::find()
.from_raw_sql(Statement::from_sql_and_values(
DbBackend::Postgres,
r#"SELECT "cake"."id", "cake"."name" FROM "cake""#,
vec![],
))
.all(&db)
.await?;
assert_eq!(
db.into_transaction_log(),
vec![Transaction::from_sql_and_values(
DbBackend::Postgres,
r#"SELECT "cake"."id", "cake"."name" FROM "cake""#,
vec![]
),]
);Trait Implementations§
source§impl<S> Clone for SelectorRaw<S>where
S: SelectorTrait + Clone,
impl<S> Clone for SelectorRaw<S>where
S: SelectorTrait + Clone,
source§fn clone(&self) -> SelectorRaw<S>
fn clone(&self) -> SelectorRaw<S>
Returns a copy of the value. Read more
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read more