sea-orm icon indicating copy to clipboard operation
sea-orm copied to clipboard

Add contains method for ActiveValue

Open negezor opened this issue 2 years ago • 6 comments

Motivation

Sometimes it is necessary to compare a value in a model that is already the active model. Now this is done somewhat inconveniently, you need to use !is_not_set() and as_ref(). Which makes the code a bit more complicated.

Proposed Solutions

let id_set = ActiveValue::Set(1);
let id_unchanged = ActiveValue::Unchanged(1);
let id_not_set = ActiveValue::<i32>::Unchanged(1);

id_set.contains(&1); // true
id_unchanged.contains(&1); // true
id_not_set.contains(&1); // false

Current Workarounds

let id_set = ActiveValue::Set(1);

!id_set.is_not_set() && id_set.as_ref() == &1

negezor avatar Mar 10 '23 16:03 negezor

In which file i will find this issue

prathamsaxen avatar Mar 13 '23 20:03 prathamsaxen

@er-pratham It's supposed to be here https://github.com/SeaQL/sea-orm/blob/master/src/entity/active_model.rs

negezor avatar Mar 13 '23 20:03 negezor

Hey @negezor, interesting. I think implementing PartialEq<T> for ActiveValue might be more conventional?

Such that we can simply write assert!(ActiveValue::Set(1) == 1).

billy1624 avatar Mar 17 '23 12:03 billy1624

Hi @billy1624, I think this behavior is confusing. It sounds like assert!(Option::Some(1) == 1) to me. I think it's worth sticking with how Option does it.

negezor avatar Mar 17 '23 15:03 negezor

@billy1624 Not sure but i did a POC please check

Outcome

    assert!(ActiveValue::Set(2) == 2);
    assert_ne!(ActiveValue::Set(2), 3);
    assert_ne!(
        ActiveValue::Unchanged(String::from("hi")),
        String::from("bye")
    );
    assert!(ActiveValue::Unchanged(String::from("hi")) == String::from("hi"));
impl<V, U> PartialEq<U> for ActiveValue<V>
where
    V: Into<Value> + std::cmp::PartialEq<U>,
    U: Into<Value>,
{
    fn eq(&self, other: &U) -> bool {
        match self {
            Self::Set(value) | Self::Unchanged(value) => value.eq(other),
            Self::NotSet => false,
        }
    }
}

Diwakar-Gupta avatar Apr 16 '23 12:04 Diwakar-Gupta

Hey @Diwakar-Gupta, the implementation looks promising!! Could you please file a PR for it?

billy1624 avatar Apr 25 '23 13:04 billy1624