ORM-16: Add dirty tracking, save() and refresh() #16

Open
opened 2026-10-13 12:49:39 +01:00 by NoctisWolfshadow · 0 comments
Owner

Depends on: #15

Context

Laravel-style persistence: change fields on a loaded model, ask whether it changed, and save() writes only what changed. The comparison is insert_values() against the snapshot held in ModelState.

Tasks

  • is_persisted(), is_dirty() (never-persisted models are dirty), is_clean(), dirty_columns() -> Vec<&'static str> and is_dirty_on(Column<Self, V>).
  • save(&mut self) -> Result<()>: not persisted means insert, set_id and snapshot; persisted and dirty means UPDATE of only the dirty columns, then snapshot; clean means no write.
  • refresh(&mut self) -> Result<()>: reload by PK and replace the fields and state. Error::NotFound if the row is gone, Error::NotPersisted for a new model.
  • Docs: NaN floats never compare equal and will always read as dirty.

Example

let mut user = User::find(1)?.unwrap();
assert!(user.is_clean());

user.name = "Alicia".into();
assert!(user.is_dirty());
assert_eq!(user.dirty_columns(), ["name"]);
assert!(user.is_dirty_on(User::NAME));
assert!(!user.is_dirty_on(User::AGE));

user.save()?;                     // UPDATE users SET name = ? WHERE id = ?
assert!(user.is_clean());

let mut frank = User::new("frank", None, 40, true);
assert!(!frank.is_persisted() && frank.is_dirty());
frank.save()?;                    // INSERT, frank.id is now set
fn save(&mut self) -> Result<()> {
    if !self.state().is_persisted() {
        let id = self.insert()?;
        self.set_id(id);
        self.sync_original();          // snapshot = insert_values()
    } else if self.is_dirty() {
        self.update_dirty()?;          // SET only the dirty columns
        self.sync_original();
    }
    Ok(())
}

Black-box proof that only dirty columns are written, without needing SQL tracing:

#[test]
fn save_writes_only_the_dirty_columns() {
    setup();
    let mut user = User::find(1).unwrap().unwrap();

    // someone else changes `age` behind the model's back
    Database::execute("UPDATE users SET age = 99 WHERE id = 1", []).unwrap();

    user.name = "Alicia".into();
    user.save().unwrap();

    let fresh = User::find(1).unwrap().unwrap();
    assert_eq!(fresh.name, "Alicia");
    assert_eq!(fresh.age, 99); // not overwritten by the stale in-memory value
}

#[test]
fn a_clean_save_writes_nothing() {
    setup();
    let mut user = User::find(1).unwrap().unwrap();
    Database::execute("UPDATE users SET name = 'changed' WHERE id = 1", []).unwrap();
    user.save().unwrap();
    assert_eq!(User::find(1).unwrap().unwrap().name, "changed");
}

Acceptance criteria

  • A new model is dirty and not persisted; after save it is clean with its id set.
  • Changing name gives dirty_columns() == ["name"].
  • The two black-box tests above pass.
  • refresh picks up an external change and returns NotFound / NotPersisted in the documented cases.
**Depends on:** #15 ## Context Laravel-style persistence: change fields on a loaded model, ask whether it changed, and `save()` writes only what changed. The comparison is `insert_values()` against the snapshot held in `ModelState`. ## Tasks - [ ] `is_persisted()`, `is_dirty()` (never-persisted models are dirty), `is_clean()`, `dirty_columns() -> Vec<&'static str>` and `is_dirty_on(Column<Self, V>)`. - [ ] `save(&mut self) -> Result<()>`: not persisted means insert, `set_id` and snapshot; persisted and dirty means UPDATE of only the dirty columns, then snapshot; clean means no write. - [ ] `refresh(&mut self) -> Result<()>`: reload by PK and replace the fields and state. `Error::NotFound` if the row is gone, `Error::NotPersisted` for a new model. - [ ] Docs: `NaN` floats never compare equal and will always read as dirty. ## Example ```rust let mut user = User::find(1)?.unwrap(); assert!(user.is_clean()); user.name = "Alicia".into(); assert!(user.is_dirty()); assert_eq!(user.dirty_columns(), ["name"]); assert!(user.is_dirty_on(User::NAME)); assert!(!user.is_dirty_on(User::AGE)); user.save()?; // UPDATE users SET name = ? WHERE id = ? assert!(user.is_clean()); let mut frank = User::new("frank", None, 40, true); assert!(!frank.is_persisted() && frank.is_dirty()); frank.save()?; // INSERT, frank.id is now set ``` ```rust fn save(&mut self) -> Result<()> { if !self.state().is_persisted() { let id = self.insert()?; self.set_id(id); self.sync_original(); // snapshot = insert_values() } else if self.is_dirty() { self.update_dirty()?; // SET only the dirty columns self.sync_original(); } Ok(()) } ``` Black-box proof that only dirty columns are written, without needing SQL tracing: ```rust #[test] fn save_writes_only_the_dirty_columns() { setup(); let mut user = User::find(1).unwrap().unwrap(); // someone else changes `age` behind the model's back Database::execute("UPDATE users SET age = 99 WHERE id = 1", []).unwrap(); user.name = "Alicia".into(); user.save().unwrap(); let fresh = User::find(1).unwrap().unwrap(); assert_eq!(fresh.name, "Alicia"); assert_eq!(fresh.age, 99); // not overwritten by the stale in-memory value } #[test] fn a_clean_save_writes_nothing() { setup(); let mut user = User::find(1).unwrap().unwrap(); Database::execute("UPDATE users SET name = 'changed' WHERE id = 1", []).unwrap(); user.save().unwrap(); assert_eq!(User::find(1).unwrap().unwrap().name, "changed"); } ``` ## Acceptance criteria - [ ] A new model is dirty and not persisted; after `save` it is clean with its id set. - [ ] Changing `name` gives `dirty_columns() == ["name"]`. - [ ] The two black-box tests above pass. - [ ] `refresh` picks up an external change and returns `NotFound` / `NotPersisted` in the documented cases.
Sign in to join this conversation.
No description provided.