Skip to content

Commit

Permalink
#129 Add set method to UpdateMany
Browse files Browse the repository at this point in the history
  • Loading branch information
tyt2y3 committed Sep 10, 2021
1 parent 1775ab4 commit f56ac7b
Showing 1 changed file with 46 additions and 2 deletions.
48 changes: 46 additions & 2 deletions src/query/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ impl<A> UpdateOne<A>
where
A: ActiveModelTrait,
{
pub(crate) fn prepare_filters(mut self) -> Self {
fn prepare_filters(mut self) -> Self {
for key in <A::Entity as EntityTrait>::PrimaryKey::iter() {
let col = key.into_column();
let av = self.model.get(col);
Expand All @@ -99,7 +99,7 @@ where
self
}

pub(crate) fn prepare_values(mut self) -> Self {
fn prepare_values(mut self) -> Self {
for col in <A::Entity as EntityTrait>::Column::iter() {
if <A::Entity as EntityTrait>::PrimaryKey::from_column(col).is_some() {
continue;
Expand Down Expand Up @@ -177,6 +177,19 @@ impl<E> UpdateMany<E>
where
E: EntityTrait,
{
pub fn set<A>(mut self, model: A) -> Self
where
A: ActiveModelTrait<Entity = E>,
{
for col in E::Column::iter() {
let av = model.get(col);
if av.is_set() {
self.query.value(col, av.unwrap());
}
}
self
}

pub fn col_expr<T>(mut self, col: T, expr: SimpleExpr) -> Self
where
T: IntoIden,
Expand Down Expand Up @@ -244,4 +257,35 @@ mod tests {
r#"UPDATE "fruit" SET "cake_id" = NULL WHERE "fruit"."id" = 2"#,
);
}

#[test]
fn update_5() {
assert_eq!(
Update::many(fruit::Entity)
.set(fruit::ActiveModel {
name: ActiveValue::set("Apple".to_owned()),
cake_id: ActiveValue::set(Some(3)),
..Default::default()
})
.filter(fruit::Column::Id.eq(2))
.build(DbBackend::Postgres)
.to_string(),
r#"UPDATE "fruit" SET "name" = 'Apple', "cake_id" = 3 WHERE "fruit"."id" = 2"#,
);
}

#[test]
fn update_6() {
assert_eq!(
Update::many(fruit::Entity)
.set(fruit::ActiveModel {
id: ActiveValue::set(3),
..Default::default()
})
.filter(fruit::Column::Id.eq(2))
.build(DbBackend::Postgres)
.to_string(),
r#"UPDATE "fruit" SET "id" = 3 WHERE "fruit"."id" = 2"#,
);
}
}

0 comments on commit f56ac7b

Please sign in to comment.