Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion crates/database/src/model/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Self>) -> impl Future<Output = Result<()>> + Send {
async { Ok(()) }
}
Expand Down
48 changes: 34 additions & 14 deletions crates/database/src/model/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,33 +230,36 @@ 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<Arithmetic> = Vec::new();
for (column, apply) in arithmetic {
let current = match applied.iter().position(|earlier| earlier.column == column) {
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)
}
}
}
Expand Down Expand Up @@ -453,22 +456,33 @@ fn single_table<M: Model>(query: Builder<M>) -> Builder<M> {
///
/// # 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<M: Model>(
model: &mut M,
key: M::Key,
before: M,
arithmetic: Vec<Arithmetic>,
location: &'static Location<'static>,
) -> Result<()> {
let event = write_changes(model, key, before, arithmetic, location).await?;
dispatch_updated(event).await
}

async fn write_changes<M: Model>(
model: &mut M,
key: M::Key,
before: M,
arithmetic: Vec<Arithmetic>,
location: &'static Location<'static>,
) -> Result<Option<Updated<M>>> {
(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);
Expand Down Expand Up @@ -500,11 +514,17 @@ pub async fn save<M: Model>(
}
query.filter(key_is::<M>(key)).update_rows(values).await?;

fire(Updated {
Ok(Some(Updated {
model: model.clone(),
changes,
})
.await
}))
}

async fn dispatch_updated<M: Model>(event: Option<Updated<M>>) -> Result<()> {
if let Some(event) = event {
fire(event).await?;
}
Ok(())
}

/// Updates `model`'s row with `values`, like a query's `update_values`.
Expand Down
3 changes: 2 additions & 1 deletion macros/model/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -784,7 +784,8 @@ pub(crate) fn expand(options: Options, mut item: ItemStruct) -> syn::Result<Toke
/// Start updating the model.
///
/// Set the columns on the returned builder, then await the builder to write the columns that
/// changed. If the write fails, the model keeps the changes, and `refresh` reloads its row.
/// changed. If the `updating` hook or the write fails, the model keeps its previous values.
/// After the write succeeds, it holds the new values even if an `Updated` listener fails.
#[track_caller]
#vis fn update(&mut self) -> #update_builder<'_> {
#update_builder(::laravel::model::UpdateBuilder::new(self))
Expand Down
7 changes: 5 additions & 2 deletions src/model/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
49 changes: 49 additions & 0 deletions tests/model_lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Updated<Member>>| 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();
Expand Down Expand Up @@ -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");
Expand Down