expression

SeaORM: update changed fields

Convert a loaded row into an ActiveModel, mark the field to change with Set, then update it. Fields kept in the Unchanged state are not requested as changes. This is a partial update, not an optimistic concurrency check; a concurrent writer may still overwrite the same column. Uses a disposable in-memory SQLite database. Expected stdout (not executed): Pen: 5 Common mistake: Assuming a partial update prevents lost updates; use a version condition or transaction strategy where needed.

Formal Syntax & Structure

rust syntaxrust
model.into_active_model(); active.stock = Set(5); active.update(&db).await

Working Example

Example Snippetrust
use sea_orm::{ActiveModelTrait, ColumnTrait, ConnectOptions, ConnectionTrait,    Database, DatabaseConnection, DbBackend, DbErr, EntityTrait, IntoActiveModel,    PaginatorTrait, QueryFilter, QueryOrder, Set, Statement};
mod item {    use sea_orm::entity::prelude::*;
    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]    #[sea_orm(table_name = "items")]    pub struct Model {        #[sea_orm(primary_key)]        pub id: i32,        pub label: String,        pub stock: i32,        pub note: Option<String>,    }    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]    pub enum Relation {}    impl ActiveModelBehavior for ActiveModel {}}
async fn sample_db() -> Result<DatabaseConnection, DbErr> {    let mut options = ConnectOptions::new("sqlite::memory:");    options.max_connections(1).min_connections(1).sqlx_logging(false);    let db = Database::connect(options).await?;    db.execute(Statement::from_string(DbBackend::Sqlite,        "CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, label TEXT NOT NULL, stock INTEGER NOT NULL CHECK(stock >= 0), note TEXT)".to_owned())).await?;    db.execute(Statement::from_string(DbBackend::Sqlite,        "INSERT INTO items (label, stock, note) VALUES ('Pen', 4, NULL), ('Pad', 0, 'blue'), ('Clip', 8, NULL)".to_owned())).await?;    Ok(db)}
#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), DbErr> {    let db = sample_db().await?;    if let Some(row) = item::Entity::find_by_id(1).one(&db).await? {        let mut active = row.into_active_model();        active.stock = Set(5);        let saved = active.update(&db).await?;        println!("{}: {}", saved.label, saved.stock);    }    Ok(())}
Rust Reference