ActiveValue

Enum ActiveValue 

pub enum ActiveValue<V>
where V: Into<Value>,
{ Set(V), Unchanged(V), NotSet, }
Expand description

The state of a field in an [ActiveModel][ActiveModelTrait].

There are three possible states represented by three enum variants:

  • Set - a value that’s explicitly set by the application and sent to the database.
  • Unchanged - an existing, unchanged value from the database.
  • NotSet - an undefined value (nothing is sent to the database).

The difference between these states is useful when constructing INSERT and UPDATE SQL statements (see an example below). It’s also useful for knowing which fields have changed in a record.

§Examples

use sea_orm::tests_cfg::{cake, fruit};
use sea_orm::{DbBackend, entity::*, query::*};

// Here, we use `NotSet` to let the database automatically generate an `id`.
// This is different from `Set(None)` that explicitly sets `cake_id` to `NULL`.
assert_eq!(
    Insert::one(fruit::ActiveModel {
        id: ActiveValue::NotSet,
        name: ActiveValue::Set("Orange".to_owned()),
        cake_id: ActiveValue::Set(None),
    })
    .build(DbBackend::Postgres)
    .to_string(),
    r#"INSERT INTO "fruit" ("name", "cake_id") VALUES ('Orange', NULL)"#
);

// Here, we update the record, set `cake_id` to the new value
// and use `NotSet` to avoid updating the `name` field.
// `id` is the primary key, so it's used in the condition and not updated.
assert_eq!(
    Update::one(fruit::ActiveModel {
        id: ActiveValue::Unchanged(1),
        name: ActiveValue::NotSet,
        cake_id: ActiveValue::Set(Some(2)),
    })
    .validate()
    .unwrap()
    .build(DbBackend::Postgres)
    .to_string(),
    r#"UPDATE "fruit" SET "cake_id" = 2 WHERE "fruit"."id" = 1"#
);

Variants§

§

Set(V)

A Value that’s explicitly set by the application and sent to the database.

Use this to insert or set a specific value.

When editing an existing value, you can use set_if_not_equals to preserve the Unchanged state when the new value is the same as the old one. Then you can meaningfully use methods like [ActiveModelTrait::is_changed].

§

Unchanged(V)

An existing, unchanged Value from the database.

You get these when you query an existing Model from the database and convert it into an [ActiveModel][ActiveModelTrait].

When you edit it, you can use set_if_not_equals to preserve this “unchanged” state if the new value is the same as the old one. Then you can meaningfully use methods like [ActiveModelTrait::is_changed].

§

NotSet

An undefined Value. Nothing is sent to the database.

When you create a new [ActiveModel][ActiveModelTrait], its fields are NotSet by default.

This can be useful when:

  • You insert a new record and want the database to generate a default value (e.g., an id).
  • In an UPDATE statement, you don’t want to update some field.

Implementations§

§

impl<V> ActiveValue<V>
where V: Into<Value>,

pub fn set(value: V) -> Self

Create an ActiveValue::Set

pub fn is_set(&self) -> bool

Check if the ActiveValue is ActiveValue::Set

pub fn unchanged(value: V) -> Self

pub fn is_unchanged(&self) -> bool

pub fn not_set() -> Self

pub fn is_not_set(&self) -> bool

pub fn take(&mut self) -> Option<V>

Take ownership of the inner value, also setting self to NotSet

pub fn unwrap(self) -> V

Get an owned value of the ActiveValue

§Panics

Panics if it is ActiveValue::NotSet

pub fn into_value(self) -> Option<Value>

Take ownership of the inner value, consuming self

pub fn into_wrapped_value(self) -> ActiveValue<Value>

Wrap the Value into a ActiveValue<Value>

pub fn reset(&mut self)

Reset the value from ActiveValue::Unchanged to ActiveValue::Set, leaving ActiveValue::NotSet untouched.

pub fn set_if_not_equals(&mut self, value: V)
where V: PartialEq,

Set(value), except when self.is_unchanged() and value equals the current Unchanged value.

This is useful when you have an Unchanged value from the database, then update it using this method, and then use .is_unchanged() to see whether it has actually changed.

The same nice effect applies to the entire ActiveModel. You can now meaningfully use [ActiveModelTrait::is_changed][ActiveModelTrait#method.is_changed] to see whether are any changes that need to be saved to the database.

§Examples
let mut value = ActiveValue::Unchanged("old");

// This wouldn't be the case if we used plain `value = Set("old");`
value.set_if_not_equals("old");
assert!(value.is_unchanged());

// Only when we change the actual `&str` value, it becomes `Set`
value.set_if_not_equals("new");
assert_eq!(value.is_unchanged(), false);
assert_eq!(value, ActiveValue::Set("new"));

pub fn set_if_not_equals_and(&mut self, value: V, f: impl FnOnce(&V) -> bool)
where V: PartialEq,

Set(value), except when self.is_unchanged(), value equals the current Unchanged value, and value does not match a given predicate.

This is useful in the same situations as ActiveValue as well as when you want to leave an existing Set value alone depending on a condition, such as ensuring a None value never replaced an existing Some value. This can come up when trying to merge two ActiveValues.

§Examples
let mut value = ActiveValue::Set(Some("old"));

// since Option::is_some(None) == false, we leave the existing set value alone
value.set_if_not_equals_and(None, Option::is_some);
assert_eq!(value, ActiveValue::Set(Some("old")));

// since Option::is_some(Some("new")) == true, we replace the set value
value.set_if_not_equals_and(Some("new"), Option::is_some);
assert_eq!(value, ActiveValue::Set(Some("new")));

pub fn try_as_ref(&self) -> Option<&V>

Get the inner value, unless self is NotSet.

There’s also a panicking version: ActiveValue::as_ref.

§Examples
assert_eq!(ActiveValue::Unchanged(42).try_as_ref(), Some(&42));
assert_eq!(ActiveValue::Set(42).try_as_ref(), Some(&42));
assert_eq!(ActiveValue::NotSet.try_as_ref(), None::<&i32>);

Trait Implementations§

§

impl<V> AsRef<V> for ActiveValue<V>
where V: Into<Value>,

§

fn as_ref(&self) -> &V

§Panics

Panics if it is ActiveValue::NotSet.

See ActiveValue::try_as_ref for a fallible non-panicking version.

§

impl<V> Clone for ActiveValue<V>
where V: Into<Value> + Clone,

§

fn clone(&self) -> ActiveValue<V>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl<V> Debug for ActiveValue<V>
where V: Into<Value> + Debug,

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
§

impl<V> Default for ActiveValue<V>
where V: Into<Value>,

§

fn default() -> Self

§

impl<V> DefaultActiveValue for ActiveValue<V>
where V: Into<Value> + ValueType + Nullable,

§

fn default_value(&self) -> Self

Default::default() if implemented, dummy value otherwise
§

impl<V> DefaultActiveValueNone for ActiveValue<Option<V>>
where V: Into<Value> + Nullable,

§

fn default_value(&self) -> Self

Always None
§

impl<V> DefaultActiveValueNotSet for &ActiveValue<V>
where V: Into<Value>,

§

type Value = ActiveValue<V>

The owned value type
§

fn default_value(&self) -> Self::Value

Always NotSet
§

impl<V> From<ActiveValue<V>> for ActiveValue<Option<V>>
where V: Into<Value> + Nullable,

§

fn from(value: ActiveValue<V>) -> Self

Converts to this type from the input type.
§

impl<V> PartialEq for ActiveValue<V>
where V: Into<Value> + PartialEq,

§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

§

impl<V> Freeze for ActiveValue<V>
where V: Freeze,

§

impl<V> RefUnwindSafe for ActiveValue<V>
where V: RefUnwindSafe,

§

impl<V> Send for ActiveValue<V>
where V: Send,

§

impl<V> Sync for ActiveValue<V>
where V: Sync,

§

impl<V> Unpin for ActiveValue<V>
where V: Unpin,

§

impl<V> UnwindSafe for ActiveValue<V>
where V: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

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

fn in_current_span(self) -> Instrumented<Self>

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

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more