Skip to main content

Update

Struct Update 

Source
pub struct Update<'a>(/* private fields */);
Expand description

Composable DynamoDB update expression builder.

Update<'a> represents a single DynamoDB update expression that can be used as an UpdateExpression. It supports all four DynamoDB update clauses — SET, REMOVE, ADD, and DELETE — and multiple actions can be combined into a single expression with and, combine, or try_combine.

Attribute names that are DynamoDB reserved words are automatically escaped with # expression attribute name placeholders.

§Display

Update implements Display in two modes:

  • Default ({}) — resolves all placeholders inline for human-readable debugging: SET balance = N("100")
  • Alternate ({:#}) — shows the raw expression with #name / :value placeholders and separate maps: SET balance = :u0\n values: { :u0 = N("100") }

§Examples

Simple SET:

use dynamodb_facade::Update;

let update = Update::set("role", "instructor");
assert_eq!(format!("{update}"), r#"SET role = S("instructor")"#);

Combining multiple actions:

use dynamodb_facade::Update;

let update = Update::set("name", "Alice")
    .and(Update::remove("legacy_field"))
    .and(Update::increment("login_count", 1));
let rendered = format!("{update}");
assert_eq!(
    format!("{update}"),
    r#"SET name = S("Alice"), login_count = login_count + N("1") REMOVE legacy_field"#,
);

Implementations§

Source§

impl<'a> Update<'a>

Source

pub fn set_custom(attr: impl Into<Cow<'a, str>>, rhs: UpdateSetRhs<'a>) -> Self

Creates a SET action with a custom right-hand-side expression.

Use this when set is insufficient — for example, to reference another attribute, use if_not_exists, or build complex arithmetic expressions. See UpdateSetRhs for the available RHS forms.

§Examples
use dynamodb_facade::{Update, UpdateSetRhs};

// SET old_score = if_not_exists(score, 0)
let update = Update::set_custom(
    "old_score",
    UpdateSetRhs::if_not_exists("score", 0),
);
assert_eq!(
    format!("{update}"),
    r#"SET old_score = if_not_exists(score, N("0"))"#
);
Source

pub fn set( attr: impl Into<Cow<'a, str>>, value: impl IntoAttributeValue, ) -> Self

Creates a SET action that assigns a literal value: SET attr = value.

§Examples
use dynamodb_facade::Update;

let update = Update::set("role", "instructor");
assert_eq!(format!("{update}"), r#"SET role = S("instructor")"#);
Source

pub fn set_if_not_exists( attr: impl Into<Cow<'a, str>>, value: impl IntoAttributeValue, ) -> Self

Creates a SET action that only writes if the attribute does not already exist.

Generates SET attr = if_not_exists(attr, value). This is an atomic “initialize if absent” operation — it will not overwrite an existing value.

§Examples
use dynamodb_facade::Update;

let update = Update::set_if_not_exists("created_at", "2024-01-01");
assert_eq!(
    format!("{update}"),
    r#"SET created_at = if_not_exists(created_at, S("2024-01-01"))"#
);
Source

pub fn increment( attr: impl Into<Cow<'a, str>>, by: impl IntoAttributeValue, ) -> Self

Creates a SET action that increments a numeric attribute: SET attr = attr + by.

The attribute must already exist and be a number. To safely initialize and increment in one operation, use init_increment.

§Examples
use dynamodb_facade::Update;

let update = Update::increment("login_count", 1);
assert_eq!(
    format!("{update}"),
    r#"SET login_count = login_count + N("1")"#
);
Source

pub fn decrement( attr: impl Into<Cow<'a, str>>, by: impl IntoAttributeValue, ) -> Self

Creates a SET action that decrements a numeric attribute: SET attr = attr - by.

The attribute must already exist and be a number. To safely initialize and decrement in one operation, use init_decrement.

§Examples
use dynamodb_facade::Update;

let update = Update::decrement("credits", 10);
assert_eq!(
    format!("{update}"),
    r#"SET credits = credits - N("10")"#
);
Source

pub fn init_increment( attr: impl Into<Cow<'a, str>>, initial: impl IntoAttributeValue, by: impl IntoAttributeValue, ) -> Self

Creates a SET action that initializes and increments atomically.

Generates SET attr = if_not_exists(attr, initial) + by. If the attribute does not exist, it is initialized to initial before the increment is applied. This is safe to call even on a new item.

§Examples
use dynamodb_facade::Update;

// SET enrollment_count = if_not_exists(enrollment_count, 0) + 1
let update = Update::init_increment("enrollment_count", 0, 1);
assert_eq!(
    format!("{update}"),
    r#"SET enrollment_count = if_not_exists(enrollment_count, N("0")) + N("1")"#
);
Source

pub fn init_decrement( attr: impl Into<Cow<'a, str>>, initial: impl IntoAttributeValue, by: impl IntoAttributeValue, ) -> Self

Creates a SET action that initializes and decrements atomically.

Generates SET attr = if_not_exists(attr, initial) - by. If the attribute does not exist, it is initialized to initial before the decrement is applied. This is safe to call even on a new item.

§Examples
use dynamodb_facade::Update;

// SET balance = if_not_exists(balance, 1000) - 50
let update = Update::init_decrement("balance", 1000, 50);
assert_eq!(
    format!("{update}"),
    r#"SET balance = if_not_exists(balance, N("1000")) - N("50")"#
);
Source

pub fn list_append( attr: impl Into<Cow<'a, str>>, value: impl IntoAttributeValue, ) -> Self

Creates a SET action that appends elements to a list attribute.

Generates SET attr = list_append(attr, value). The value must be a DynamoDB List (L) attribute value.

§Examples
use dynamodb_facade::Update;

let update = Update::list_append("tags", vec!["rust"]);
assert_eq!(
    format!("{update}"),
    r#"SET tags = list_append(tags, L([S("rust")]))"#
);
Source

pub fn list_prepend( attr: impl Into<Cow<'a, str>>, value: impl IntoAttributeValue, ) -> Self

Creates a SET action that prepends elements to a list attribute.

Generates SET attr = list_append(value, attr). The value must be a DynamoDB List (L) attribute value.

§Examples
use dynamodb_facade::Update;

let update = Update::list_prepend("notifications", vec!["new_event"]);
assert_eq!(
    format!("{update}"),
    r#"SET notifications = list_append(L([S("new_event")]), notifications)"#
);
Source

pub fn remove(attr: impl Into<Cow<'a, str>>) -> Self

Creates a REMOVE action that deletes an attribute from the item.

Generates REMOVE attr. The attribute path may include a list index (e.g. "tags[2]") to remove a specific list element.

§Examples
use dynamodb_facade::Update;

let update = Update::remove("legacy_field");
assert_eq!(format!("{update}"), "REMOVE legacy_field");

let update = Update::remove("tags[2]");
assert_eq!(format!("{update}"), "REMOVE tags[2]");
Source

pub fn list_remove(attr: impl Into<Cow<'a, str>>, index: usize) -> Self

Creates a REMOVE action that deletes a specific element from a list attribute.

Generates REMOVE attr[index]. The index is zero-based.

§Examples
use dynamodb_facade::Update;

let update = Update::list_remove("tags", 2);
assert_eq!(format!("{update}"), "REMOVE tags[2]");
Source

pub fn add( attr: impl Into<Cow<'a, str>>, value: impl IntoAttributeValue, ) -> Self

Creates an ADD action for numeric attributes or set attributes.

For numeric attributes, generates ADD attr value which atomically adds value to the current attribute value (initializing to zero if absent). For DynamoDB Set types (SS, NS, BS), adds elements to the set.

§Examples
use dynamodb_facade::Update;

let update = Update::add("visitor_count", 5);
assert_eq!(format!("{update}"), r#"ADD visitor_count N("5")"#);
Source

pub fn delete( attr: impl Into<Cow<'a, str>>, value: impl IntoAttributeValue, ) -> Self

Creates a DELETE action that removes elements from a DynamoDB Set attribute.

Generates DELETE attr set. The value must be a DynamoDB Set type (SS, NS, or BS). Elements present in value are removed from the set attribute.

§Examples
use dynamodb_facade::{AsSet, Update};

// Remove "rust" from the tag_set (SS attribute).
let update = Update::delete("tag_set", AsSet(vec!["rust"]));
assert_eq!(format!("{update}"), r#"DELETE tag_set Ss(["rust"])"#);
Source

pub fn and(self, other: Update<'a>) -> Self

Chains another update action onto this one.

The resulting expression merges all SET, REMOVE, ADD, and DELETE actions from both updates into a single UpdateExpression. Existing Combine wrappers are flattened.

§Examples
use dynamodb_facade::Update;

let update = Update::set("name", "Alice")
    .and(Update::set("role", "instructor"))
    .and(Update::remove("legacy_field"));

assert_eq!(
    format!("{update}"),
    r#"SET name = S("Alice"), role = S("instructor") REMOVE legacy_field"#,
);
Source

pub fn combine(updates: impl IntoIterator<Item = Update<'a>>) -> Self

Combines an iterator of updates into a single update expression.

All SET, REMOVE, ADD, and DELETE actions from the iterator are merged into one UpdateExpression.

§Panics

Panics if the iterator is empty. Use try_combine for a non-panicking alternative.

§Examples
use dynamodb_facade::Update;

let update = Update::combine([
    Update::set("name", "Alice"),
    Update::set("role", "instructor"),
    Update::remove("legacy_field"),
]);

assert_eq!(
    format!("{update}"),
    r#"SET name = S("Alice"), role = S("instructor") REMOVE legacy_field"#,
);

Combining optional updates from an iterator:

use dynamodb_facade::Update;

let new_name: Option<&str> = Some("Alice");
let new_email: Option<&str> = None;

let update = Update::combine(
    [
        new_name.map(|n| Update::set("name", n)),
        new_email.map(|e| Update::set("email", e)),
    ]
    .into_iter()
    .flatten(),
);
assert_eq!(format!("{update}"), r#"SET name = S("Alice")"#);
Source

pub fn try_combine( updates: impl IntoIterator<Item = Update<'a>>, ) -> Option<Self>

Combines an iterator of updates into a single update expression, returning None if empty.

This is the non-panicking version of combine. Returns None when the iterator yields no items, which is useful when all updates are conditional and none may apply.

§Examples
use dynamodb_facade::Update;

let new_name: Option<&str> = None;
let new_address: Option<&str> = None;

// No updates — returns None.
let update = Update::try_combine(
    [
        new_name.map(|n| Update::set("name", n)),
        new_address.map(|a| Update::set("address", a))
    ]
    .into_iter()
    .flatten(),
);
assert!(update.is_none());

// At least one update — returns Some.
let update = Update::try_combine([Update::set("role", "admin")]);
assert!(update.is_some());

Trait Implementations§

Source§

impl<'a> Clone for Update<'a>

Source§

fn clone(&self) -> Update<'a>

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
Source§

impl<'a> Debug for Update<'a>

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Display for Update<'_>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'a> Freeze for Update<'a>

§

impl<'a> RefUnwindSafe for Update<'a>

§

impl<'a> Send for Update<'a>

§

impl<'a> Sync for Update<'a>

§

impl<'a> Unpin for Update<'a>

§

impl<'a> UnsafeUnpin for Update<'a>

§

impl<'a> UnwindSafe for Update<'a>

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<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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<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