diff --git a/crates/database/src/model/lifecycle.rs b/crates/database/src/model/lifecycle.rs index 1c6a4782c..0a558beaa 100644 --- a/crates/database/src/model/lifecycle.rs +++ b/crates/database/src/model/lifecycle.rs @@ -78,7 +78,8 @@ pub trait Hooks: Sized + Send + Sync + 'static { /// /// # Errors /// - /// An error stops the write, and the update returns it. The model keeps its changes. + /// An error stops the write and returns to the caller. The model keeps the values it had + /// before the update. fn updating(&mut self, _changes: &Changes) -> impl Future> + Send { async { Ok(()) } } diff --git a/crates/database/src/model/update.rs b/crates/database/src/model/update.rs index 4ca4f467a..386ffb671 100644 --- a/crates/database/src/model/update.rs +++ b/crates/database/src/model/update.rs @@ -230,16 +230,16 @@ impl<'a, M: Model> IntoFuture for UpdateBuilder<'a, M> { quietly, location, } = self; - let updated = async move { + let update = async move { let key = key_of(model); - let before = model.clone(); + let mut updated = model.clone(); let mut set = Vec::new(); for value in values.resolve().await? { set.push(value.column()); - value.apply(model); + value.apply(&mut updated); } for parent in parents { - parent(model)?; + parent(&mut updated)?; } let mut applied: Vec = Vec::new(); for (column, apply) in arithmetic { @@ -247,16 +247,19 @@ impl<'a, M: Model> IntoFuture for UpdateBuilder<'a, M> { Some(earlier) => applied.remove(earlier).expr, None => col(column), }; - applied.push(apply(model, current)); + applied.push(apply(&mut updated, current)); } applied.retain(|arithmetic| !set.contains(&arithmetic.column)); - save(model, key, before, applied, location).await + let before = model.__without_relations(); + let event = write_changes(&mut updated, key, before, applied, location).await?; + *model = updated; + dispatch_updated(event).await }; if quietly { - Box::pin(super::without_events(updated)) + Box::pin(super::without_events(update)) } else { - Box::pin(updated) + Box::pin(update) } } } @@ -453,7 +456,7 @@ fn single_table(query: Builder) -> Builder { /// /// # Errors /// -/// Returns an error when the `updating` hook, the `UPDATE` query, or the `updated` hook fails. +/// Returns an error when the `updating` hook, the `UPDATE` query, or an `Updated` listener fails. pub async fn save( model: &mut M, key: M::Key, @@ -461,14 +464,25 @@ pub async fn save( arithmetic: Vec, location: &'static Location<'static>, ) -> Result<()> { + let event = write_changes(model, key, before, arithmetic, location).await?; + dispatch_updated(event).await +} + +async fn write_changes( + model: &mut M, + key: M::Key, + before: M, + arithmetic: Vec, + location: &'static Location<'static>, +) -> Result>> { (M::META.keep_ciphertexts)(model, &before); let changes = Changes::between(before, model.clone()); if changes.is_empty() { - return Ok(()); + return Ok(None); } model.updating(&changes).await?; if changes.undone_by(model) { - return Ok(()); + return Ok(None); } let query = query_of(model).called_at(location); @@ -500,11 +514,17 @@ pub async fn save( } query.filter(key_is::(key)).update_rows(values).await?; - fire(Updated { + Ok(Some(Updated { model: model.clone(), changes, - }) - .await + })) +} + +async fn dispatch_updated(event: Option>) -> Result<()> { + if let Some(event) = event { + fire(event).await?; + } + Ok(()) } /// Updates `model`'s row with `values`, like a query's `update_values`. diff --git a/macros/model/src/model.rs b/macros/model/src/model.rs index 47d1c8e46..13c75cc4e 100644 --- a/macros/model/src/model.rs +++ b/macros/model/src/model.rs @@ -784,7 +784,8 @@ pub(crate) fn expand(options: Options, mut item: ItemStruct) -> syn::Result #update_builder<'_> { #update_builder(::laravel::model::UpdateBuilder::new(self)) diff --git a/src/model/mod.rs b/src/model/mod.rs index cde8c22b2..057d58293 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -587,8 +587,11 @@ pub use laravel_rust_model_macros::row; /// `views -= 1` add and subtract in the database, as `views = views + 1`, like `increment` and /// `decrement`. /// -/// After the update, the model holds the new values. If the write fails, the model keeps them, -/// and `refresh` reloads its row. +/// If the `updating` hook or the write returns an error, the model keeps its previous values. +/// After a constraint violation, you can resolve the conflict and retry on the same instance. +/// If the connection drops during the write, check the row on the write connection before +/// retrying because the database may already have applied the update. Once the database confirms +/// the write, the model holds the new values even if an [`Updated`] listener returns an error. /// /// When you pass a model query instead of a model, the macro updates every row the query matches /// without loading the rows, and returns the number of rows it changed. The fields work the same diff --git a/tests/model_lifecycle.rs b/tests/model_lifecycle.rs index 7d4b4d7d5..ff9d62ad6 100644 --- a/tests/model_lifecycle.rs +++ b/tests/model_lifecycle.rs @@ -408,6 +408,54 @@ async fn each_write_dispatches_its_event_once_with_the_model() -> laravel::Resul .await } +#[tokio::test] +async fn a_failed_update_can_be_retried_on_the_same_model() -> laravel::Result<()> { + let app = app(); + app.travel_to(at("2026-11-03T09:00:00Z")); + + app.scope(async || { + create_tables().await?; + let mut alice = create!(User { ..new_user("Alice") }).await?; + let bob = create!(User { ..new_user("Bob") }).await?; + + app.travel_to(at("2026-11-03T10:00:00Z")); + let error = update!(alice { ..new_user("Bob") }).await.unwrap_err(); + assert!(db::is_unique_violation(&error)); + assert_eq!(alice.name, "Alice"); + assert_eq!(alice.email, "alice@laravel.com"); + assert_eq!(alice.updated_at, at("2026-11-03T09:00:00Z")); + + bob.delete().await?; + update!(alice { ..new_user("Bob") }).await?; + let stored = User::find_or_fail(alice.id).await?; + assert_eq!(stored.name, "Bob"); + assert_eq!(stored.email, "bob@laravel.com"); + assert_eq!(stored.updated_at, at("2026-11-03T10:00:00Z")); + Ok(()) + }) + .await +} + +#[tokio::test] +async fn the_model_keeps_the_written_values_when_an_updated_listener_fails() -> laravel::Result<()> { + let app = configure() + .with_events(|events, _| { + events.listen(|_: Event>| async { Err::<(), _>(laravel::abort(503)) }); + }) + .create(); + + app.scope(async || { + create_tables().await?; + let mut member = create!(Member { name: "Alice" }).await?; + let error = update!(member { name: "Bob" }).await.unwrap_err(); + assert_eq!(error.status(), 503); + assert_eq!(member.name, "Bob"); + assert_eq!(Member::find_or_fail(member.id).await?.name, "Bob"); + Ok(()) + }) + .await +} + #[tokio::test] async fn changes_read_typed_values_from_before_and_after_the_update() -> laravel::Result<()> { let app = app(); @@ -676,6 +724,7 @@ async fn a_hook_error_stops_the_write_and_reaches_the_caller() -> laravel::Resul let mut article = taylor.articles().create().fill(new_article("Hello")).await?; let error = update!(article { title: "Forbidden" }).await.unwrap_err(); assert_eq!(error.status(), 422); + assert_eq!(article.title, "Hello"); assert_eq!(Article::find_or_fail(article.id).await?.title, "Hello"); let mut locked = new_article("Locked");