From e024db4fc6e03933e90250f83e3a9df5e8e81315 Mon Sep 17 00:00:00 2001 From: TharinduWijayarathna Date: Wed, 2 Dec 2026 03:27:54 +0530 Subject: [PATCH] Add soft deletes to models --- crates/database/src/db/builder.rs | 14 ++ crates/database/src/model/mod.rs | 35 ++++ crates/database/src/model/query.rs | 7 + crates/database/src/model/soft_delete.rs | 193 +++++++++++++++++++ crates/database/src/model/update.rs | 7 +- crates/database/src/model/write.rs | 22 +-- docs/models.md | 70 +++++++ macros/model/src/model.rs | 102 +++++++++- src/model/mod.rs | 19 +- tests/model_soft_deletes.rs | 230 +++++++++++++++++++++++ tests/suite_database.rs | 2 + 11 files changed, 669 insertions(+), 32 deletions(-) create mode 100644 crates/database/src/model/soft_delete.rs create mode 100644 tests/model_soft_deletes.rs diff --git a/crates/database/src/db/builder.rs b/crates/database/src/db/builder.rs index 83fc29246..03042b010 100644 --- a/crates/database/src/db/builder.rs +++ b/crates/database/src/db/builder.rs @@ -172,6 +172,8 @@ pub struct Builder { pub(crate) timestamps: Timestamps, /// The table whose columns a model query returns, which its aggregates count distinct rows of. pub(crate) model_table: Option<&'static str>, + /// Whether the query's first filter leaves out soft deleted rows, which `with_trashed` removes. + pub(crate) trashed_scope: bool, model: PhantomData M>, } @@ -182,6 +184,7 @@ impl Clone for Builder { creates: self.creates.clone(), timestamps: self.timestamps, model_table: self.model_table, + trashed_scope: self.trashed_scope, ..self.retyped() } } @@ -354,6 +357,7 @@ impl Builder { creates: Creates::default(), timestamps: Timestamps::default(), model_table: None, + trashed_scope: false, model: PhantomData, } } @@ -370,6 +374,7 @@ impl Builder { creates: Creates::default(), timestamps: Timestamps::default(), model_table: None, + trashed_scope: false, model: PhantomData, } } @@ -385,6 +390,7 @@ impl Builder { creates: Creates::default(), timestamps: Timestamps::default(), model_table: None, + trashed_scope: false, model: PhantomData, } } @@ -393,9 +399,17 @@ impl Builder { pub(crate) fn reading(&self, from: impl Into) -> Self { let mut query = self.clone(); query.select = Select::new(from.into()); + query.trashed_scope = false; query } + /// Removes the filter that leaves out soft deleted rows, if the query has it. + pub(crate) fn without_trashed_scope(&mut self) { + if std::mem::take(&mut self.trashed_scope) { + self.select.filter.remove(0); + } + } + /// A query of this query's rows, as a subquery under `alias`, on the same connection. pub(crate) fn wrapped(&self, alias: &str) -> Self { self.reading(sub(self.clone(), alias)) diff --git a/crates/database/src/model/mod.rs b/crates/database/src/model/mod.rs index 3e0a8e7ad..fe739a0e8 100644 --- a/crates/database/src/model/mod.rs +++ b/crates/database/src/model/mod.rs @@ -18,6 +18,7 @@ mod morph; pub mod query; mod queued; mod relation; +mod soft_delete; mod update; #[doc(hidden)] pub mod write; @@ -86,6 +87,9 @@ pub use self::relation::{ pub use self::relation::{ Eager, ForeignKey, IntoAggregate, IntoCount, IntoEager, IntoHas, ModelList, Relation, RelationQuery, }; +pub use self::soft_delete::SoftDeletes; +#[doc(hidden)] +pub use self::soft_delete::{__force_delete, __restore}; #[doc(hidden)] pub use self::update::save; #[doc(hidden)] @@ -174,6 +178,9 @@ pub struct Meta { pub created_at: Option>, /// The column that holds when the row last changed, if the model has one. pub updated_at: Option>, + /// The column that holds when the row was soft deleted, if the model is + /// `#[model(soft_deletes)]`. + pub deleted_at: Option>, /// Restores the previous ciphertext of each [`Encrypted`](crate::crypt::Encrypted) column /// whose update set the same value it already encrypted. pub keep_ciphertexts: fn(&mut M, &M), @@ -197,6 +204,14 @@ pub struct Field { pub relations: &'static [&'static str], } +/// The soft delete column of a [`Meta`], with a function that sets the column's value on a model. +pub struct SoftDelete { + /// The column's name. + pub name: &'static str, + /// Sets the model's field to when the row was deleted, or to `None` when it's restored. + pub set: fn(&mut M, Option), +} + /// A timestamp column of a [`Meta`], with a function that sets the column's value on a model. pub struct Stamp { /// The column's name. @@ -227,6 +242,7 @@ impl fmt::Debug for Meta { .field("columns", &self.columns) .field("created_at", &self.created_at) .field("updated_at", &self.updated_at) + .field("deleted_at", &self.deleted_at) .finish() } } @@ -237,6 +253,20 @@ impl fmt::Debug for Field { } } +impl Clone for SoftDelete { + fn clone(&self) -> Self { + *self + } +} + +impl Copy for SoftDelete {} + +impl fmt::Debug for SoftDelete { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.debug_tuple("SoftDelete").field(&self.name).finish() + } +} + impl fmt::Debug for Stamp { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.debug_tuple("Stamp").field(&self.name).finish() @@ -251,6 +281,11 @@ where value.into() } +#[doc(hidden)] +pub fn __soft_delete>(deleted_at: Option) -> Option { + deleted_at.map(T::from) +} + #[doc(hidden)] pub fn __stamp>(now: Timestamp) -> T { T::from(now) diff --git a/crates/database/src/model/query.rs b/crates/database/src/model/query.rs index 13c5c87ad..d7846e403 100644 --- a/crates/database/src/model/query.rs +++ b/crates/database/src/model/query.rs @@ -22,6 +22,10 @@ pub fn __query() -> Builder { let mut query = Builder::new(on::(), Source::from(M::META.table)); query.timestamps = Timestamps::of::(); query.model_table = Some(M::META.table); + if let Some(deleted_at) = M::META.deleted_at { + query.select.filter.push(super::soft_delete::not_trashed(deleted_at)); + query.trashed_scope = true; + } query } @@ -116,8 +120,11 @@ pub(crate) fn table_of() -> Builder { /// Returns a query of `M` on the connection that `model` was read from, for the model's own writes /// and reloads. +/// +/// The query finds the model's row even when it's soft deleted. pub fn query_of(model: &M) -> Builder { let mut query = __query::(); + query.without_trashed_scope(); if let Some(name) = &model.__connection().0 { query.on = On::Named(name.to_string()); } diff --git a/crates/database/src/model/soft_delete.rs b/crates/database/src/model/soft_delete.rs new file mode 100644 index 000000000..bb38909ec --- /dev/null +++ b/crates/database/src/model/soft_delete.rs @@ -0,0 +1,193 @@ +//! Soft deletes, which mark a row as deleted with a timestamp instead of removing it. +//! +//! A `#[model(soft_deletes)]` model's queries leave out the rows whose `deleted_at` is set, and its +//! `delete` sets the column instead of removing the row. + +use std::panic::Location; + +use futures_util::future::Either; + +use super::lifecycle::{Deleted, fire}; +use super::query::{key_is, query_of}; +use super::update::single_table; +use super::write::key_of; +use super::{Model, SoftDelete}; +use crate::Result; +use crate::db::{Builder, Condition, Expr, Values}; +use crate::time::Timestamp; + +/// A model whose rows are soft deleted, which `#[model(soft_deletes)]` implements. +/// +/// The model's queries leave out soft deleted rows, unless they call +/// [`with_trashed`](Builder::with_trashed) or [`only_trashed`](Builder::only_trashed). +pub trait SoftDeletes: Model {} + +/// Returns the soft delete column of `M`, which `#[model(soft_deletes)]` always declares. +fn column() -> SoftDelete { + M::META + .deleted_at + .expect("`#[model(soft_deletes)]` declares the `deleted_at` column") +} + +/// Returns the condition that a row of `M` isn't soft deleted. +pub(crate) fn not_trashed(deleted_at: SoftDelete) -> Condition { + Expr::qualified(M::META.table, deleted_at.name).is_null() +} + +/// Returns the values that soft delete a row at `now`, and touch its `updated_at`. +fn trashing(deleted_at: SoftDelete, now: Timestamp) -> Values { + let values = Values::new().set(deleted_at.name, now); + match M::META.updated_at { + Some(updated_at) => values.set(updated_at.name, now), + None => values, + } +} + +/// Returns the values that restore a soft deleted row at `now`. +fn restoring(deleted_at: SoftDelete, now: Timestamp) -> Values { + let values = Values::new().set(deleted_at.name, None::); + match M::META.updated_at { + Some(updated_at) => values.set(updated_at.name, now), + None => values, + } +} + +/// Query methods of models whose rows are soft deleted. +impl Builder { + /// Includes soft deleted rows in the query's results. + /// + /// ```no_run + /// # use laravel::model::model; + /// # use laravel::time::Timestamp; + /// # #[model(soft_deletes)] pub struct Post { pub id: i64, pub deleted_at: Option } + /// # async fn example() -> laravel::Result<()> { + /// let every_post = Post::query().with_trashed().get().await?; + /// # Ok(()) } + /// ``` + pub fn with_trashed(mut self) -> Self { + self.without_trashed_scope(); + self + } + + /// Returns only the soft deleted rows. + /// + /// ```no_run + /// # use laravel::model::model; + /// # use laravel::time::Timestamp; + /// # #[model(soft_deletes)] pub struct Post { pub id: i64, pub deleted_at: Option } + /// # async fn example() -> laravel::Result<()> { + /// let trashed = Post::query().only_trashed().get().await?; + /// # Ok(()) } + /// ``` + pub fn only_trashed(self) -> Self { + self.with_trashed().filter(!not_trashed(column::())) + } + + /// Restores the soft deleted rows that the query matches, and returns the number of restored + /// rows. + /// + /// The restore reaches soft deleted rows without [`only_trashed`](Self::only_trashed), and + /// leaves rows that aren't deleted as they are. It runs no hooks and dispatches no events. + /// + /// ```no_run + /// # use laravel::model::model; + /// # use laravel::time::Timestamp; + /// # #[model(soft_deletes)] pub struct Post { pub id: i64, pub user_id: i64, pub deleted_at: Option } + /// # async fn example() -> laravel::Result<()> { + /// let restored = Post::query().filter(Post::user_id.eq(1)).restore().await?; + /// # Ok(()) } + /// ``` + /// + /// # Errors + /// + /// Returns the same errors as [`update_values`](Self::update_values). + #[track_caller] + pub fn restore(&self) -> impl Future> + use { + let location = self.call_site(); + self.clone() + .called_at(location) + .only_trashed() + .update_values(restoring(column::(), crate::now().timestamp())) + } + + /// Removes every row that the query matches from the table, rather than soft deleting it, + /// and returns the number of removed rows. + /// + /// The query leaves out soft deleted rows unless it calls [`with_trashed`](Self::with_trashed) + /// or [`only_trashed`](Self::only_trashed) first. Like [`delete`](Self::delete), it runs no + /// hooks and dispatches no events. + /// + /// # Errors + /// + /// Returns the same errors as [`delete`](Self::delete). + #[track_caller] + pub fn force_delete(&self) -> impl Future> + use { + single_table(self.clone().called_at(self.call_site())).delete_rows() + } +} + +impl Builder { + /// Deletes the rows the query matches: soft deletes them when the model has soft deletes, and + /// removes them otherwise. + pub(crate) fn delete_or_trash(&self) -> impl Future> + use { + let query = single_table(self.clone().called_at(self.call_site())); + match M::META.deleted_at { + Some(deleted_at) => Either::Left(query.update_rows(trashing(deleted_at, crate::now().timestamp()))), + None => Either::Right(query.delete_rows()), + } + } +} + +/// Deletes the model's row after the `deleting` hook, dispatches `Deleted`, and returns the number +/// of deleted rows. +/// +/// A soft deleting model's row gets its `deleted_at`, unless `force` removes the row anyway. +pub(crate) async fn delete(mut model: M, force: bool, location: &'static Location<'static>) -> Result { + model.deleting().await?; + let query = query_of(&model).called_at(location).filter(key_is::(key_of(&model))); + let deleted = match M::META.deleted_at { + Some(deleted_at) if !force => { + let now = crate::now().timestamp(); + let deleted = query.update_rows(trashing(deleted_at, now)).await?; + (deleted_at.set)(&mut model, Some(now)); + if let Some(updated_at) = M::META.updated_at { + (updated_at.set)(&mut model, now); + } + deleted + } + _ => single_table(query).delete_rows().await?, + }; + fire(Deleted { model }).await?; + + Ok(deleted) +} + +#[doc(hidden)] +#[track_caller] +pub fn __force_delete(model: M) -> impl Future> + Send { + let location = Location::caller(); + async move { + delete(model, true, location).await?; + Ok(()) + } +} + +#[doc(hidden)] +#[track_caller] +pub fn __restore(model: &mut M) -> impl Future> + Send + '_ { + let location = Location::caller(); + let now = crate::now().timestamp(); + let deleted_at = column::(); + let write = query_of(model) + .called_at(location) + .filter(key_is::(key_of(model))) + .update_rows(restoring(deleted_at, now)); + async move { + write.await?; + (deleted_at.set)(model, None); + if let Some(updated_at) = M::META.updated_at { + (updated_at.set)(model, now); + } + Ok(()) + } +} diff --git a/crates/database/src/model/update.rs b/crates/database/src/model/update.rs index 4ca4f467a..62d7bfd2b 100644 --- a/crates/database/src/model/update.rs +++ b/crates/database/src/model/update.rs @@ -428,7 +428,7 @@ impl std::fmt::Debug for MassUpdateBuilder { /// The subquery reads the keys through a derived table. MySQL can't update a table that a /// subquery reads directly, as a self-relation's `has` does, and it rejects a `LIMIT` directly /// inside `IN`. -fn single_table(query: Builder) -> Builder { +pub(super) fn single_table(query: Builder) -> Builder { let select = &query.select; let filters_its_table = select.joins.is_empty() && !select.filter.iter().any(Condition::has_subquery) @@ -592,6 +592,9 @@ impl Builder { /// Deletes every row that the query matches, without loading the rows, and returns the number /// of deleted rows. /// + /// A `#[model(soft_deletes)]` model's rows get their `deleted_at` and `updated_at` instead, and + /// [`force_delete`](Self::force_delete) removes them. + /// /// The delete runs no hooks and dispatches no events. When the query joins other tables, /// filters with a subquery, orders, limits, or offsets, it deletes the rows whose keys the /// query selects, like [`update`](Self::update). Examples include a `#[belongs_to_many]` @@ -611,7 +614,7 @@ impl Builder { /// Returns an error when the query has a `having` or a union, or when the query fails. #[track_caller] pub fn delete(&self) -> impl Future> + use { - single_table(self.clone().called_at(self.call_site())).delete_rows() + self.delete_or_trash() } /// Starts an update that adds `amount` to `column` in every row the query matches, as diff --git a/crates/database/src/model/write.rs b/crates/database/src/model/write.rs index be9ac00ff..95c0102a4 100644 --- a/crates/database/src/model/write.rs +++ b/crates/database/src/model/write.rs @@ -9,9 +9,9 @@ use std::panic::Location; use super::Entries; use super::create::{CreateBuilder, IntoCreate, IntoRow, PASS_PARENTS}; -use super::lifecycle::{Deleted, Draft, fire}; +use super::lifecycle::Draft; use super::many_to_many::runs; -use super::query::{__query, key_is, query_of, table_of}; +use super::query::{__query, query_of, table_of}; use super::update::Updates; use super::{Column, ColumnsOf, Model}; use crate::Result; @@ -504,25 +504,11 @@ column_tuples!( pub fn __delete(model: M) -> impl Future> + Send { let location = Location::caller(); async move { - delete(model, location).await?; + super::soft_delete::delete(model, false, location).await?; Ok(()) } } -/// Deletes the model's row after the `deleting` hook, dispatches `Deleted`, and returns the number -/// of deleted rows. -async fn delete(model: M, location: &'static Location<'static>) -> Result { - model.deleting().await?; - let deleted = query_of(&model) - .called_at(location) - .filter(key_is::(key_of(&model))) - .delete() - .await?; - fire(Deleted { model }).await?; - - Ok(deleted) -} - #[doc(hidden)] #[track_caller] pub fn __destroy( @@ -533,7 +519,7 @@ pub fn __destroy( async move { let mut deleted = 0; for model in models.await? { - deleted += delete(model, location).await?; + deleted += super::soft_delete::delete(model, false, location).await?; } Ok(deleted) diff --git a/docs/models.md b/docs/models.md index 33dc0d189..2b8d25939 100644 --- a/docs/models.md +++ b/docs/models.md @@ -36,6 +36,7 @@ - [Updating many rows](#updating-many-rows) - [Reloading from the database](#reloading-from-the-database) - [Deleting models](#deleting-models) + - [Soft deleting](#soft-deleting) - [Serializing models](#serializing-models) - [Hooks](#hooks) - [Events](#events) @@ -1447,6 +1448,75 @@ let drafts = Post::query() update!(drafts { published_at: laravel::now() }).await?; ``` + +### Soft deleting + +Instead of removing a row, you may soft delete it: Laravel sets the row's `deleted_at` column, and your queries leave the row out from then on. Add `soft_deletes` to `#[model]`, give the model a `deleted_at: Option` field, and add the column with `soft_deletes()` in a [migration](migrations.md): + +```rust +use laravel::model::model; +use laravel::time::Timestamp; + +#[model(soft_deletes)] +pub struct Post { + pub id: i64, + pub title: String, + pub created_at: Timestamp, + pub updated_at: Timestamp, + pub deleted_at: Option, +} +``` + +```rust +tx.schema() + .alter("posts", |table| { + table.soft_deletes(); + }) + .await +``` + +Now `delete` sets `deleted_at` and `updated_at` to the current time rather than removing the row. It still runs the `deleting` [hook](#hooks) and dispatches `Deleted`, and the event's model reports `trashed()` as `true`. A query's `delete` soft deletes the rows it matches, too: + +```rust +post.delete().await?; + +Post::query().filter(Post::votes.eq(0)).delete().await?; +``` + +Every query of the model leaves out soft deleted rows, including `find`, route model binding, relationship queries, eager loads, `with_count`, and `has` filters. To include them, call `with_trashed`, and to read only them, call `only_trashed`: + +```rust +let posts = Post::query().with_trashed().get().await?; + +let trashed = Post::query().only_trashed().get().await?; + +let comments = post.comments().with_trashed().get().await?; +``` + +`trashed` tells you whether a model you hold is soft deleted. `restore` clears its `deleted_at`, and `force_delete` removes its row for good, running the `deleting` hook and dispatching `Deleted` as `delete` does: + +```rust +let mut post = Post::query().only_trashed().find_or_fail(id).await?; + +if post.trashed() { + post.restore().await?; +} + +post.force_delete().await?; +``` + +Queries have `restore` and `force_delete` as well. A query's `restore` reaches soft deleted rows without `only_trashed`, and leaves rows that aren't deleted as they are. Like other query writes, neither runs hooks or dispatches events: + +```rust +Post::query().filter(Post::user_id.eq(user.id)).restore().await?; + +Post::query().only_trashed().filter(Post::deleted_at.lt(cutoff)).force_delete().await?; +``` + +A model's own writes and reloads, such as `update!`, `refresh`, and `restore`, reach its row even after it's soft deleted. When a `#[belongs_to]` relation's parent model may be soft deleted, declare it as `BelongsTo>`, because eager loading leaves out a trashed parent. + +`with_trashed`, `only_trashed`, `restore`, and `force_delete` only exist on models with `soft_deletes`, so calling them on another model is a compile error. A soft deleting model's fields can't be named `trashed`, `restore`, or `force_delete`. + ## Serializing models diff --git a/macros/model/src/model.rs b/macros/model/src/model.rs index 47d1c8e46..c355a60ff 100644 --- a/macros/model/src/model.rs +++ b/macros/model/src/model.rs @@ -9,7 +9,7 @@ use syn::{Attribute, Field, Fields, Ident, ItemStruct, LitStr, Meta, Path, Token use crate::relation::{Marker, Relation, Rename, Serde}; use crate::syntax; -/// `#[model(table = "..", connection = "..", route_key = "..", morph = "..", hooks)]`. +/// `#[model(table = "..", connection = "..", route_key = "..", morph = "..", hooks, soft_deletes)]`. #[derive(Default)] pub(crate) struct Options { table: Option, @@ -19,6 +19,8 @@ pub(crate) struct Options { morph: Option, /// The application implements `Hooks` for the model. hooks: bool, + /// The model's `deleted_at` column marks soft deleted rows. + soft_deletes: bool, /// The model is searchable, and the application implements `Searchable` for it. searchable: Option, } @@ -43,10 +45,17 @@ impl Parse for Options { options.hooks = true; continue; } + Meta::Path(path) if path.is_ident("soft_deletes") => { + if options.soft_deletes { + return Err(syn::Error::new_spanned(path, "`soft_deletes` is given twice")); + } + options.soft_deletes = true; + continue; + } option => { return Err(syn::Error::new_spanned( option, - "expected an option such as `table = \"people\"`: `table`, `connection`, `route_key`, `morph`, `hooks` or `searchable`", + "expected an option such as `table = \"people\"`: `table`, `connection`, `route_key`, `morph`, `hooks`, `soft_deletes` or `searchable`", )); } }; @@ -59,7 +68,7 @@ impl Parse for Options { _ => { return Err(syn::Error::new_spanned( &option.path, - "`#[model]` takes `table`, `connection`, `route_key`, `morph`, `hooks` and `searchable`", + "`#[model]` takes `table`, `connection`, `route_key`, `morph`, `hooks`, `soft_deletes` and `searchable`", )); } }; @@ -113,6 +122,10 @@ const GENERATED: &[&str] = &[ "factory", ]; +/// The methods `#[model(soft_deletes)]` adds to the struct. A soft deleting model's field can't +/// share their names. +const SOFT_DELETES: &[&str] = &["force_delete", "restore", "trashed"]; + /// A field that's a column of the model's table. pub(crate) struct Column { pub(crate) ident: Ident, @@ -193,6 +206,11 @@ pub(crate) fn expand(options: Options, mut item: ItemStruct) -> syn::Result syn::Result::__NAMES.len())); quote!(&::laravel::model::__concat_fields::(&[#(#parts),*])) }; + let deleted_at = match soft_deletes { + Some(Column { ident, ty, name, .. }) => quote_spanned! {ty.span()=> + ::core::option::Option::Some(::laravel::model::SoftDelete:: { + name: #name, + set: |__laravel_model, __laravel_deleted_at| { + __laravel_model.#ident = ::laravel::model::__soft_delete(__laravel_deleted_at); + }, + }) + }, + None => quote!(::core::option::Option::None), + }; + let soft_delete_methods = soft_deletes.map(|Column { ident, .. }| { + quote! { + impl ::laravel::model::SoftDeletes for #name {} + + impl #name { + /// Whether the model's row is soft deleted. + #[must_use] + #vis fn trashed(&self) -> bool { + ::core::option::Option::is_some(&self.#ident) + } + + /// Remove the model's row from the table, rather than soft deleting it. + /// + /// Like `delete`, it runs the `deleting` hook and dispatches `Deleted`. + #[track_caller] + #vis fn force_delete(self) -> impl ::core::future::Future> + ::core::marker::Send { + ::laravel::model::__force_delete(self) + } + + /// Restore the model's soft deleted row, clearing its `deleted_at`. + /// + /// The restore runs no hooks and dispatches no events. + #[track_caller] + #vis fn restore(&mut self) -> impl ::core::future::Future> + ::core::marker::Send + '_ { + ::laravel::model::__restore(self) + } + } + } + }); let created_at = stamp(&columns, "created_at"); let updated_at = stamp(&columns, "updated_at"); let encrypted = columns @@ -585,6 +643,7 @@ pub(crate) fn expand(options: Options, mut item: ItemStruct) -> syn::Result syn::Result( + columns: &'a [Column], + fields: &Punctuated, + model: &Ident, +) -> syn::Result<&'a Column> { + for field in fields { + if let Some(ident) = &field.ident + && SOFT_DELETES.contains(&ident.unraw().to_string().as_str()) + { + return Err(syn::Error::new_spanned( + ident, + format!( + "`{ident}` is the name of a method that `#[model(soft_deletes)]` generates; rename the field and \ + keep its column with `#[column(\"{ident}\")]`" + ), + )); + } + } + let Some(column) = columns.iter().find(|column| column.ident == "deleted_at") else { + return Err(syn::Error::new_spanned( + model, + "`#[model(soft_deletes)]` requires a `deleted_at: Option` field", + )); + }; + if !column.optional { + return Err(syn::Error::new_spanned( + &column.ident, + "`deleted_at` must be an `Option`, such as `Option`, because a row that isn't deleted holds NULL", + )); + } + + Ok(column) +} + fn stamp(columns: &[Column], field: &str) -> TokenStream { match columns.iter().find(|column| column.ident == field) { Some(Column { ident, ty, name, .. }) => quote_spanned! {ty.span()=> diff --git a/src/model/mod.rs b/src/model/mod.rs index cde8c22b2..393efdac0 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -43,13 +43,13 @@ pub use laravel_database::model::{ __BelongsTo, __Connection, __Counts, __Date, __Embed, __Embedded, __Has, __HasMany, __Json, __MorphVariant, __PicksOrOwns, __Reaches, __ReachesRows, __Related, __RelationMethod, __Text, __Time, __Variant, __Vector, __concat_fields, __create_many, __delete, __destroy, __distinct_morphs, __find, __first_or_create, __for_morph, - __fresh, __hop, __insert, __is, __key, __load, __method_id, __morph_pair, __prefixed_bytes, __prefixed_len, - __prefixed_names, __query, __refresh, __require_columns, __serde, __stamp, __update_or_create, __update_values, - __upsert, __value, AnyRelation, Assignments, Children, ColumnsOf, CreateBuilder, Decrement, Definition, Embed, - FillRef, FillTarget, Hop, Increment, Inverse, IsMorphQuery, JoinColumn, JoinItem, JoinMorph, JoinMorphField, - JoinMorphPath, JoinRows, JoinTable, MassUpdateBuilder, MorphField, MorphPair, MorphParent, MorphShared, MorphSlot, - MorphToRelation, Null, OfMany, Parent, ParentQuery, QueryTable, RelationKeys, Scope, SerdeRename, Shared, Slot, - UpdateBuilder, Updates, Variant, joined, + __force_delete, __fresh, __hop, __insert, __is, __key, __load, __method_id, __morph_pair, __prefixed_bytes, + __prefixed_len, __prefixed_names, __query, __refresh, __require_columns, __restore, __serde, __soft_delete, + __stamp, __update_or_create, __update_values, __upsert, __value, AnyRelation, Assignments, Children, ColumnsOf, + CreateBuilder, Decrement, Definition, Embed, FillRef, FillTarget, Hop, Increment, Inverse, IsMorphQuery, + JoinColumn, JoinItem, JoinMorph, JoinMorphField, JoinMorphPath, JoinRows, JoinTable, MassUpdateBuilder, MorphField, + MorphPair, MorphParent, MorphShared, MorphSlot, MorphToRelation, Null, OfMany, Parent, ParentQuery, QueryTable, + RelationKeys, Scope, SerdeRename, Shared, Slot, UpdateBuilder, Updates, Variant, joined, }; #[doc(inline)] pub use laravel_database::model::{ @@ -60,8 +60,8 @@ pub use laravel_database::model::{ IntoMorph, IntoMorphParent, IntoParent, IntoRow, JoinMorphColumns, JoinRow, JoinValues, Joined, JoinedQuery, KeySource, Many, ManyToMany, Meta, Model, ModelKey, ModelList, ModelNotFound, Morph, MorphEager, MorphKey, MorphMany, MorphOf, MorphOne, MorphQuery, MorphRelation, MorphTo, MorphToMany, MorphType, MorphedByMany, Numeric, - Ordered, Relation, RelationCount, RelationQuery, Replica, Stamp, SyncChanges, Unique, UpdateValue, Updated, - without_events, + Ordered, Relation, RelationCount, RelationQuery, Replica, SoftDelete, SoftDeletes, Stamp, SyncChanges, Unique, + UpdateValue, Updated, without_events, }; /// Derives [`Fill`], which fills a model's columns from a struct's fields of the same names. @@ -326,6 +326,7 @@ pub use laravel_rust_model_macros::join_row; /// | `connection = ".."` | The connection queries run on, instead of the default connection | /// | `route_key = ".."` | The field that route model binding finds the model by, instead of the key. A route's `{post:slug}` names another for that route | /// | `hooks` | You implement [`Hooks`] for the model. Without it, the macro implements the defaults | +/// | `soft_deletes` | `delete` sets the `deleted_at: Option` field's column instead of removing the row, and queries leave out those rows. The macro implements [`SoftDeletes`] and adds `trashed`, `restore`, and `force_delete` | /// | `#[key]` | The key field, instead of `id` | /// | `#[column("..")]` | The field's column, instead of the field's name | /// | `#[default]` | The database supplies the column's value when an insert leaves it out | diff --git a/tests/model_soft_deletes.rs b/tests/model_soft_deletes.rs new file mode 100644 index 000000000..21087c22b --- /dev/null +++ b/tests/model_soft_deletes.rs @@ -0,0 +1,230 @@ +use std::sync::Mutex; + +use laravel::config::database::ConnectionConfig; +use laravel::container::Inject; +use laravel::db; +use laravel::event::Event; +use laravel::model::{Deleted, HasMany, create, model}; +use laravel::testing::prelude::*; +use laravel::time::Timestamp; + +#[model(soft_deletes)] +pub struct Post { + pub id: i64, + pub title: String, + pub created_at: Timestamp, + pub updated_at: Timestamp, + pub deleted_at: Option, + #[has_many] + pub comments: HasMany, +} + +#[model(soft_deletes)] +pub struct Comment { + pub id: i64, + pub post_id: i64, + pub body: String, + pub deleted_at: Option, +} + +#[derive(Default)] +struct Recorded(Mutex>); + +impl Recorded { + fn take(&self) -> Vec { + std::mem::take(&mut *self.0.lock().unwrap()) + } +} + +fn app() -> Application { + Application::configure() + .for_testing(env!("CARGO_MANIFEST_DIR")) + .with_config(|config, _| { + let mut connection = ConnectionConfig::new("sqlite::memory:"); + connection.max_connections = 1; + config.database.default = "app".into(); + config.database.add_connection("app", connection); + }) + .with_services(|app| { + app.instance(Recorded::default()); + }) + .with_events(|events, _| { + events.listen(|event: Event>, recorded: Inject| async move { + let state = if event.model.trashed() { "trashed" } else { "removed" }; + recorded + .0 + .lock() + .unwrap() + .push(format!("deleted {} {state}", event.model.title)); + }); + }) + .create() +} + +async fn create_tables() -> laravel::Result<()> { + let connection = db::default_connection()?; + connection + .schema() + .create("posts", |table| { + table.id(); + table.string("title"); + table.timestamps(); + table.soft_deletes(); + }) + .await?; + connection + .schema() + .create("comments", |table| { + table.id(); + table.big_integer("post_id"); + table.string("body"); + table.soft_deletes(); + }) + .await?; + + Ok(()) +} + +async fn titles(query: db::Builder) -> laravel::Result> { + let posts = query.order_by(Post::id).get().await?; + Ok(posts.into_iter().map(|post| post.title).collect()) +} + +fn at(time: &str) -> Timestamp { + time.parse().unwrap() +} + +#[tokio::test] +async fn deleting_a_model_trashes_its_row_and_queries_leave_it_out() -> laravel::Result<()> { + let app = app(); + let recorded = app.resolve::().await; + app.travel_to(at("2026-12-01T09:00:00Z")); + + app.scope(async || { + create_tables().await?; + let draft = create!(Post { title: "Draft" }).await?; + create!(Post { title: "Published" }).await?; + let draft_id = draft.id; + + app.travel_to(at("2026-12-02T10:00:00Z")); + draft.delete().await?; + assert_eq!(recorded.take(), ["deleted Draft trashed"]); + + assert_eq!(titles(Post::query()).await?, ["Published"]); + assert_eq!(Post::query().count().await?, 1); + assert!(Post::find(draft_id).await?.is_none()); + assert!(Post::find_or_fail(draft_id).await.is_err()); + assert_eq!(titles(Post::query().with_trashed()).await?, ["Draft", "Published"]); + assert_eq!(titles(Post::query().only_trashed()).await?, ["Draft"]); + + let trashed = Post::query().with_trashed().find_or_fail(draft_id).await?; + assert!(trashed.trashed()); + assert_eq!(trashed.deleted_at, Some(at("2026-12-02T10:00:00Z"))); + assert_eq!(trashed.updated_at, at("2026-12-02T10:00:00Z")); + assert_eq!(db::table("posts").count().await?, 2, "the row stays in the table"); + + Ok(()) + }) + .await +} + +#[tokio::test] +async fn a_trashed_model_restores_refreshes_and_force_deletes() -> laravel::Result<()> { + let app = app(); + let recorded = app.resolve::().await; + app.travel_to(at("2026-12-01T09:00:00Z")); + + app.scope(async || { + create_tables().await?; + let post = create!(Post { title: "Draft" }).await?; + let id = post.id; + post.delete().await?; + recorded.take(); + + let mut post = Post::query().only_trashed().find_or_fail(id).await?; + post.refresh().await?; + assert!(post.trashed(), "a trashed model reloads its own row"); + + app.travel_to(at("2026-12-03T08:00:00Z")); + post.restore().await?; + assert!(!post.trashed()); + assert_eq!(post.updated_at, at("2026-12-03T08:00:00Z")); + assert_eq!(Post::find_or_fail(id).await?.deleted_at, None); + + post.force_delete().await?; + assert_eq!(recorded.take(), ["deleted Draft removed"]); + assert_eq!(db::table("posts").count().await?, 0); + + Ok(()) + }) + .await +} + +#[tokio::test] +async fn query_deletes_trash_rows_and_query_restores_and_force_deletes_reach_them() -> laravel::Result<()> { + let app = app(); + app.travel_to(at("2026-12-01T09:00:00Z")); + + app.scope(async || { + create_tables().await?; + for title in ["First", "Second", "Third"] { + create!(Post { title }).await?; + } + + let trashed = Post::query().filter(Post::title.ne("Third")).delete().await?; + assert_eq!(trashed, 2); + assert_eq!(titles(Post::query()).await?, ["Third"]); + assert_eq!(db::table("posts").count().await?, 3); + + let restored = Post::query().filter(Post::title.ne("Second")).restore().await?; + assert_eq!(restored, 1, "only the trashed row that the filter matches"); + assert_eq!(titles(Post::query()).await?, ["First", "Third"]); + + assert_eq!(Post::query().only_trashed().force_delete().await?, 1); + assert_eq!(titles(Post::query().with_trashed()).await?, ["First", "Third"]); + + Ok(()) + }) + .await +} + +#[tokio::test] +async fn relations_leave_out_trashed_related_rows() -> laravel::Result<()> { + let app = app(); + + app.scope(async || { + create_tables().await?; + let post = create!(Post { title: "Post" }).await?; + create!(Comment { + post_id: post.id, + body: "Kept" + }) + .await?; + let spam = create!(Comment { + post_id: post.id, + body: "Spam" + }) + .await?; + spam.delete().await?; + + let post = Post::query() + .with(Post::comments) + .with_count(Post::comments) + .first_or_fail() + .await?; + let bodies: Vec<&str> = post.comments.iter().map(|comment| comment.body.as_str()).collect(); + assert_eq!(bodies, ["Kept"]); + assert_eq!(post.comments.count(), 1); + + assert_eq!(post.comments().count().await?, 1); + assert_eq!(post.comments().with_trashed().count().await?, 2); + assert_eq!( + Post::query().filter(Post::comments.exists()).count().await?, + 1, + "a post with a trashed comment still has a kept one" + ); + + Ok(()) + }) + .await +} diff --git a/tests/suite_database.rs b/tests/suite_database.rs index dfad73862..512437a05 100644 --- a/tests/suite_database.rs +++ b/tests/suite_database.rs @@ -41,6 +41,8 @@ mod model_queries; #[cfg(feature = "database-sqlite")] mod model_relations; #[cfg(feature = "database-sqlite")] +mod model_soft_deletes; +#[cfg(feature = "database-sqlite")] mod model_through; #[cfg(feature = "database-sqlite")] mod models;