Skip to main content

Update

Derive Macro Update 

Source
#[derive(Update)]
{
    // Attributes available to this derive:
    #[sql]
}
Expand description

Defines update data for a table.

Implements Update for the struct and &Struct, for use in query! and query_lazy!. Field names map to table columns, and only the fields you define are updated. Option<T> values are bound as-is, so None sets the column to NULL.

§Basic usage

#[derive(Update)]
#[sql(table = ExampleTable)]
struct UpdateData {
    name: String,
    active: bool,
}

let id = 1;
let update = UpdateData {
    name: "updated".to_string(),
    active: false,
};

query!(&mut conn,
    UPDATE ExampleTable SET {update} WHERE ExampleTable.id = {id}
)
.await?;

§Partial updates

Define a smaller update struct to update a subset of columns. Use &data if you need to reuse the update payload for multiple queries.

#[derive(Update)]
#[sql(table = ExampleTable)]
struct UpdateNickname {
    nickname: Option<String>,
}

let id = 1;
let update = UpdateNickname { nickname: None };

query!(&mut conn,
    UPDATE ExampleTable SET {&update} WHERE ExampleTable.id = {id}
)
.await?;

§Field attributes

  • #[sql(bytes)] must match #[sql(bytes)] on the table struct, stores the field as a binary blob using bincode + serde.
  • #[sql(maybe_update)] / #[sql(maybe)] marks an Option<T> field as optional: None skips the update while Some(value) updates the column. For nullable columns you can also use Option<Option<T>> to allow Some(None) to set NULL.

§Notes

  • #[sql(table = TableStruct)] is required and must point to a Table type.