diff --git a/crates/database/src/db.rs b/crates/database/src/db.rs index 5476c5134..12e4feb7f 100644 --- a/crates/database/src/db.rs +++ b/crates/database/src/db.rs @@ -50,7 +50,7 @@ pub use self::builder::{ pub use self::builder::{ BuilderInternals, ColumnTest, ConditionInternals, ExprInternals, Operator, OrderInternals, Test, }; -pub(crate) use self::builder::{ColumnName, ExprKind, On, Requalify, SourceKind, row_number}; +pub(crate) use self::builder::{ColumnName, ConditionKind, ExprKind, On, Requalify, SourceKind, row_number}; pub(crate) use self::builder::{Creates, Entries, Loader, Timestamps}; pub use self::callbacks::{AfterCommitError, after_commit}; pub use self::connection::Connection; diff --git a/crates/database/src/db/builder.rs b/crates/database/src/db/builder.rs index 83fc29246..80531f0b5 100644 --- a/crates/database/src/db/builder.rs +++ b/crates/database/src/db/builder.rs @@ -25,7 +25,7 @@ pub use self::expr::{ pub use self::internals::{BuilderInternals, ColumnTest, ConditionInternals, ExprInternals, OrderInternals, Test}; pub(crate) use self::model::{Creates, Entries, Loader, Timestamps}; -pub(crate) use self::expr::{ColumnName, ExprKind, Requalify, SourceKind, row_number}; +pub(crate) use self::expr::{ColumnName, ConditionKind, ExprKind, Requalify, SourceKind, row_number}; /// Start a query on a table of the default connection. /// diff --git a/crates/database/src/model/lifecycle.rs b/crates/database/src/model/lifecycle.rs index 1c6a4782c..02b079d73 100644 --- a/crates/database/src/model/lifecycle.rs +++ b/crates/database/src/model/lifecycle.rs @@ -92,6 +92,16 @@ pub trait Hooks: Sized + Send + Sync + 'static { fn deleting(&self) -> impl Future> + Send { async { Ok(()) } } + + /// Runs before `restore` clears the `deleted_at` of a model declared with + /// `#[model(soft_deletes)]`. + /// + /// # Errors + /// + /// An error stops the restore, and `restore` returns it. + fn restoring(&self) -> impl Future> + Send { + async { Ok(()) } + } } /// The columns that a create is about to insert into a row of model `M`, which @@ -397,6 +407,14 @@ pub struct Deleted { pub model: M, } +/// The event that `restore` dispatches after clearing the `deleted_at` of a model declared with +/// `#[model(soft_deletes)]`. +#[derive(Clone, Debug)] +pub struct Restored { + /// The restored model. + pub model: M, +} + tokio::task_local! { static MUTED: (); } diff --git a/crates/database/src/model/mod.rs b/crates/database/src/model/mod.rs index 3e0a8e7ad..58fd9a05c 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; @@ -53,7 +54,7 @@ pub use self::faker::{FakeInteger, Faker, Unique}; pub use self::join_row::{IntoJoinValue, JoinRow, JoinValues, Joined, JoinedQuery}; #[doc(hidden)] pub use self::join_row::{JoinColumn, JoinItem}; -pub use self::lifecycle::{Change, Changes, Created, Deleted, Draft, Hooks, Updated, without_events}; +pub use self::lifecycle::{Change, Changes, Created, Deleted, Draft, Hooks, Restored, Updated, without_events}; pub use self::loaded::{ BelongsTo, BelongsToMany, HasMany, HasManyThrough, HasOne, HasOneThrough, MorphMany, MorphOne, MorphToMany, MorphedByMany, @@ -87,6 +88,9 @@ pub use self::relation::{ Eager, ForeignKey, IntoAggregate, IntoCount, IntoEager, IntoHas, ModelList, Relation, RelationQuery, }; #[doc(hidden)] +pub use self::soft_delete::{__force_delete, __restore, __trashed}; +pub use self::soft_delete::{SoftDelete, SoftDeletes}; +#[doc(hidden)] pub use self::update::save; #[doc(hidden)] pub use self::update::{__update_values, MassUpdateBuilder, UpdateBuilder, Updates}; @@ -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 declared with + /// `#[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), @@ -227,6 +234,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() } } diff --git a/crates/database/src/model/query.rs b/crates/database/src/model/query.rs index 13c5c87ad..4826973f5 100644 --- a/crates/database/src/model/query.rs +++ b/crates/database/src/model/query.rs @@ -22,7 +22,7 @@ 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); - query + super::soft_delete::scoped(query) } /// Returns the connection that queries of `M` run on. @@ -116,8 +116,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 includes soft-deleted rows, so that a soft-deleted model can still save, reload, and +/// restore its row. pub fn query_of(model: &M) -> Builder { - let mut query = __query::(); + let mut query = super::soft_delete::unscoped(__query::()); 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..76db0fe2d --- /dev/null +++ b/crates/database/src/model/soft_delete.rs @@ -0,0 +1,222 @@ +//! Soft deletes, which mark a model's row as deleted by setting its `deleted_at` column instead of +//! removing the row. +//! +//! `#[model(soft_deletes)]` turns them on. Each query of the model then leaves out the rows whose +//! `deleted_at` is set, unless it calls [`with_trashed`](Builder::with_trashed) or +//! [`only_trashed`](Builder::only_trashed). + +use std::panic::Location; +use std::sync::Arc; + +use super::Model; +use super::lifecycle::{Deleted, Restored, fire}; +use super::query::{key_is, query_of}; +use super::write::key_of; +use crate::Result; +use crate::db::{Builder, Condition, ConditionKind, Values, col}; +use crate::time::Timestamp; + +/// The `deleted_at` column of a model declared with `#[model(soft_deletes)]`, with functions that +/// read and set the column's value on a model. +pub struct SoftDelete { + /// The column's name. + pub name: &'static str, + /// Sets the model's field to a time, or to `None`. + pub set: fn(&mut M, Option), + /// Whether the model's field holds a time. + pub trashed: fn(&M) -> bool, +} + +impl std::fmt::Debug for SoftDelete { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.debug_tuple("SoftDelete").field(&self.name).finish() + } +} + +/// A model declared with `#[model(soft_deletes)]`, whose queries leave out soft-deleted rows. +/// +/// `#[model(soft_deletes)]` implements this trait. +#[diagnostic::on_unimplemented( + message = "`{Self}` doesn't soft delete", + label = "expected a model declared with `#[model(soft_deletes)]`", + note = "add `soft_deletes` to `#[model(..)]` and a `deleted_at: Option` field" +)] +pub trait SoftDeletes: Model {} + +/// Marks the condition that leaves soft-deleted rows out of a query, so that `with_trashed` can +/// remove it. +struct Scope; + +/// Returns the condition on `M`'s `deleted_at` column, qualified by the model's table so that it +/// still names the model's column in a query that joins other tables. +fn deleted_at(soft: &SoftDelete) -> crate::db::Expr { + col(format!("{}.{}", M::META.table, soft.name)) +} + +/// Leaves out `M`'s soft-deleted rows from `query`, when `M` soft deletes. +pub(crate) fn scoped(query: Builder) -> Builder { + match &M::META.deleted_at { + Some(soft) => query.filter(deleted_at(soft).is_null().typed(Arc::new(Scope))), + None => query, + } +} + +/// Removes the condition that [`scoped`] adds, so `query` also returns soft-deleted rows. +pub(crate) fn unscoped(mut query: Builder) -> Builder { + query.select.filter.retain(|condition| !is_scope(condition)); + query +} + +fn is_scope(condition: &Condition) -> bool { + matches!(&condition.0, ConditionKind::Typed(_, marker) if (**marker).is::()) +} + +/// Query methods of a model declared with `#[model(soft_deletes)]`. +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 posts = Post::query().with_trashed().get().await?; + /// # Ok(()) } + /// ``` + pub fn with_trashed(self) -> Self { + unscoped(self) + } + + /// Returns only 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 { + let query = unscoped(self); + match &M::META.deleted_at { + Some(soft) => query.filter(deleted_at(soft).is_not_null()), + None => query, + } + } + + /// Clears `deleted_at` on every row the query matches, including soft-deleted rows, and + /// returns the number of rows it changed. + /// + /// Like [`update`](Self::update), the restore 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: u64 = 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(); + let name = M::META.deleted_at.as_ref().map_or("deleted_at", |soft| soft.name); + unscoped(self.clone()) + .called_at(location) + .update_values(Values::new().set(name, None::)) + } + + /// Removes every row the query matches from the database, instead of setting their + /// `deleted_at`, and returns the number of deleted rows. + /// + /// Like Eloquent's `forceDelete`, it removes soft-deleted rows that match too, without calling + /// [`with_trashed`](Self::with_trashed). 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 { + super::update::delete_rows(unscoped(self.clone()).called_at(self.call_site())) + } +} + +/// Returns whether `model`'s row is soft deleted. +#[doc(hidden)] +pub fn __trashed(model: &M) -> bool { + M::META.deleted_at.as_ref().is_some_and(|soft| (soft.trashed)(model)) +} + +/// Clears `model`'s `deleted_at`, after the `restoring` hook, and dispatches `Restored`. +#[doc(hidden)] +#[track_caller] +pub fn __restore(model: &mut M) -> impl Future> + Send + '_ { + let location = Location::caller(); + async move { + let Some(soft) = &M::META.deleted_at else { + return Ok(()); + }; + model.restoring().await?; + let now = crate::now().timestamp(); + query_of(model) + .called_at(location) + .filter(key_is::(key_of(model))) + .update_values(touched::(Values::new().set(soft.name, None::), now)) + .await?; + (soft.set)(model, None); + touch(model, now); + fire(Restored { model: model.clone() }).await + } +} + +/// Sets `model`'s `deleted_at` to now, and returns the number of rows it changed. +pub(crate) async fn trash(model: &mut M, location: &'static Location<'static>) -> Result { + let Some(soft) = &M::META.deleted_at else { + return Ok(0); + }; + let now = crate::now().timestamp(); + let trashed = query_of(model) + .called_at(location) + .filter(key_is::(key_of(model))) + .update_values(touched::(Values::new().set(soft.name, now), now)) + .await?; + (soft.set)(model, Some(now)); + touch(model, now); + Ok(trashed) +} + +/// `values`, with the model's `updated_at` set to `now`, so the row and the model get the same +/// time. +fn touched(values: Values, now: Timestamp) -> Values { + match &M::META.updated_at { + Some(stamp) => values.set(stamp.name, now), + None => values, + } +} + +/// Sets the model's `updated_at` to `now`, as the write that [`touched`] built set the row's. +fn touch(model: &mut M, now: Timestamp) { + if let Some(stamp) = &M::META.updated_at { + (stamp.set)(model, now); + } +} + +/// Removes `model`'s row, even when the model soft deletes, after the `deleting` hook, and +/// dispatches `Deleted`. +#[doc(hidden)] +#[track_caller] +pub fn __force_delete(model: M) -> impl Future> + Send { + let location = Location::caller(); + async move { + model.deleting().await?; + let query = query_of(&model).called_at(location).filter(key_is::(key_of(&model))); + super::update::delete_rows(query).await?; + fire(Deleted { model }).await + } +} diff --git a/crates/database/src/model/update.rs b/crates/database/src/model/update.rs index 4ca4f467a..b2a737e18 100644 --- a/crates/database/src/model/update.rs +++ b/crates/database/src/model/update.rs @@ -428,6 +428,11 @@ 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`. +/// Removes the rows that `query` matches, even when the model soft deletes. +pub(crate) fn delete_rows(query: Builder) -> impl Future> + use { + single_table(query).delete_rows() +} + fn single_table(query: Builder) -> Builder { let select = &query.select; let filters_its_table = select.joins.is_empty() @@ -606,12 +611,26 @@ impl Builder { /// # Ok(()) } /// ``` /// + /// When the model is declared with `#[model(soft_deletes)]`, the delete sets `deleted_at` on + /// the rows instead of removing them. Call [`force_delete`](Self::force_delete) to remove them. + /// /// # Errors /// /// 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() + let query = self.clone().called_at(self.call_site()); + let soft = M::META.deleted_at.as_ref().map(|soft| soft.name); + async move { + match soft { + Some(name) => { + query + .update_values(Values::new().set(name, crate::now().timestamp())) + .await + } + None => delete_rows(query).await, + } + } } /// 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..6b6a75470 100644 --- a/crates/database/src/model/write.rs +++ b/crates/database/src/model/write.rs @@ -511,13 +511,19 @@ pub fn __delete(model: M) -> impl Future> + Send { /// 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 { +/// +/// A model declared with `#[model(soft_deletes)]` sets its `deleted_at` instead. +async fn delete(mut 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?; + let deleted = if M::META.deleted_at.is_some() { + super::soft_delete::trash(&mut model, location).await? + } else { + query_of(&model) + .called_at(location) + .filter(key_is::(key_of(&model))) + .delete() + .await? + }; fire(Deleted { model }).await?; Ok(deleted) diff --git a/docs/models.md b/docs/models.md index 33dc0d189..d715cb324 100644 --- a/docs/models.md +++ b/docs/models.md @@ -36,6 +36,9 @@ - [Updating many rows](#updating-many-rows) - [Reloading from the database](#reloading-from-the-database) - [Deleting models](#deleting-models) + - [Soft deleting](#soft-deleting) + - [Querying soft-deleted models](#querying-soft-deleted-models) + - [Restoring and permanently deleting](#restoring-and-permanently-deleting) - [Serializing models](#serializing-models) - [Hooks](#hooks) - [Events](#events) @@ -1447,6 +1450,109 @@ let drafts = Post::query() update!(drafts { published_at: laravel::now() }).await?; ``` + +### Soft deleting + +Instead of removing rows from your database, you may "soft delete" a model. A soft-deleted model keeps its row, but its `deleted_at` column holds the time it was deleted, and queries leave it out. To enable soft deletes, add `soft_deletes` to `#[model]` and declare a `deleted_at` field: + +```rust +use laravel::model::model; +use laravel::time::Timestamp; + +#[model(soft_deletes)] +pub struct Post { + pub id: i64, + pub title: String, + pub deleted_at: Option, +} +``` + +The [`soft_deletes`](schema.md#column-types) schema method adds the nullable `deleted_at` column to the table: + +```rust +schema.table("posts", |table| { + table.soft_deletes(); +}).await?; +``` + +Now, `delete` sets the model's `deleted_at` to the current time instead of removing its row. It still runs the `deleting` [hook](#hooks) and dispatches `Deleted`, and the model in the event reports `trashed()` as `true`. Deleting through a query, such as `Post::query().filter(..).delete()`, also sets `deleted_at` on every matching row, along with `updated_at` when the model has one. + +Call `trashed` to determine whether a model you loaded has been soft deleted: + +```rust +if post.trashed() { + // ... +} +``` + + +### Querying soft-deleted models + +Every query of a soft-deleting model leaves out soft-deleted rows automatically. This includes `find`, [route model binding](#route-model-binding), and relationship queries, eager loads, counts, and `has` filters on the model. To include soft-deleted rows, call `with_trashed` on the query: + +```rust +let posts = Post::query() + .with_trashed() + .filter(Post::author_id.eq(user.id)) + .get() + .await?; +``` + +`with_trashed` also works on relationship queries and on the query that constrains an eager load or a count: + +```rust +let posts = user.posts().with_trashed().get().await?; + +let users = User::query() + .with_count(User::posts.query(|posts| posts.with_trashed())) + .get() + .await?; +``` + +To retrieve only soft-deleted rows, call `only_trashed`: + +```rust +let trashed = Post::query().only_trashed().get().await?; +``` + +The condition names the model's table, as in `posts.deleted_at is null`, so it keeps working when a query joins other tables that also have a `deleted_at` column. A model's own writes and reloads, such as `update!`, `refresh`, and `fresh`, always reach its row, even when the model is soft deleted. + + +### Restoring and permanently deleting + +To "un-delete" a soft-deleted model, call `restore`. It clears `deleted_at` in both the database and the model, runs the `restoring` hook, and dispatches a `Restored` event: + +```rust +let mut post = Post::query().only_trashed().find_or_fail(id).await?; + +post.restore().await?; +``` + +You may also restore many rows with a query. Like other query writes, it runs no hooks and dispatches no events. A query's `restore` includes soft-deleted rows, so you don't need to call `with_trashed` first: + +```rust +Post::query().filter(Post::author_id.eq(user.id)).restore().await?; +``` + +To remove a soft-deleting model's row from the database for good, call `force_delete`. It runs the `deleting` hook and dispatches `Deleted`, like `delete`: + +```rust +post.force_delete().await?; +``` + +A query's `force_delete` removes every matching row without loading the models. It also removes matching rows that are already soft deleted, so you don't need to call `with_trashed` first: + +```rust +use laravel::time::{Dates, ToSpan}; + +// Permanently remove posts that were soft deleted over 30 days ago... +Post::query() + .only_trashed() + .filter(Post::deleted_at.lt(laravel::now().minus(30.days()).timestamp())) + .force_delete() + .await?; +``` + ## Serializing models @@ -1559,14 +1665,15 @@ impl Hooks for Article { | --- | --- | --- | | `creating` | A `Draft` of the columns about to be inserted | Before an insert | | `updating` | The model with its changes, and the `Changes` | Before an update. The update also writes the changes the hook makes to the model | -| `deleting` | The model | Before the delete | +| `deleting` | The model | Before the delete, including a soft delete and `force_delete` | +| `restoring` | The model | Before `restore` clears a [soft-deleted](#soft-deleting) model's `deleted_at` | Because no model instance exists before an insert, `creating` receives a `Draft` instead of `&mut Self`. Call `draft.get(column)` to inspect a pending column value (returning `Option`) and `draft.set(column, value)` to modify it. Implementing both `creating` and `updating` keeps `slug` in sync when a record is inserted and whenever its title changes. ## Events -After each single-model write, Laravel dispatches a `Created`, `Updated`, or `Deleted` [event](events.md) from `laravel::model`. Register a listener to react to model writes without coupling side effects to your handlers, such as sending a welcome email whenever a new user signs up: +After each single-model write, Laravel dispatches a `Created`, `Updated`, `Deleted`, or `Restored` [event](events.md) from `laravel::model`. Register a listener to react to model writes without coupling side effects to your handlers, such as sending a welcome email whenever a new user signs up: ```rust // src/listeners/send_welcome_email.rs @@ -1644,8 +1751,9 @@ Hooks and events run only for writes that operate on model instances. Bulk query | `create!`, `create`, lists, related models, and creates through a relationship | `creating` for each row | `Created` for each row | | `first_or_create` and `update_or_create` | `creating` on insert, `updating` on update | `Created` on insert, `Updated` on update | | `update!`, `update`, `increment`, and `decrement` | `updating` | `Updated` | -| `delete` and `destroy` | `deleting` | `Deleted` for each model | -| `insert`, `upsert`, `update_values`, and `update!`, `update`, and `delete` on a query | None | None | +| `delete`, `destroy`, and `force_delete` | `deleting` | `Deleted` for each model | +| `restore` | `restoring` | `Restored` | +| `insert`, `upsert`, `update_values`, and `update!`, `update`, `delete`, `restore`, and `force_delete` on a query | None | None | ## Testing diff --git a/macros/model/src/model.rs b/macros/model/src/model.rs index 47d1c8e46..93b4b930b 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, + /// Deleting the model sets its `deleted_at` column instead of removing its row. + 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`", )); } }; @@ -284,6 +293,7 @@ pub(crate) fn expand(options: Options, mut item: ItemStruct) -> syn::Result syn::Result syn::Result TokenStream { } } +/// The `deleted_at` of the model's `Meta`, and the methods that `#[model(soft_deletes)]` adds. +fn soft_deletes( + enabled: bool, + name: &Ident, + vis: &syn::Visibility, + columns: &[Column], +) -> syn::Result<(TokenStream, Option)> { + if !enabled { + return Ok((quote!(::core::option::Option::None), None)); + } + let Some(Column { + ident, + ty, + name: column, + .. + }) = columns.iter().find(|column| column.ident == "deleted_at") + else { + return Err(syn::Error::new_spanned( + name, + "`#[model(soft_deletes)]` requires a `deleted_at: Option` field", + )); + }; + let meta = quote_spanned! {ty.span()=> + ::core::option::Option::Some(::laravel::model::SoftDelete:: { + name: #column, + set: |__laravel_model, __laravel_at| { + __laravel_model.#ident = ::core::option::Option::map(__laravel_at, ::laravel::model::__stamp); + }, + trashed: |__laravel_model| ::core::option::Option::is_some(&__laravel_model.#ident), + }) + }; + let result = quote!(::laravel::Result); + let future = quote!(impl ::core::future::Future); + let send = quote!(::core::marker::Send); + for column in columns { + if ["trashed", "restore", "force_delete"] + .iter() + .any(|method| column.ident == method) + { + return Err(syn::Error::new_spanned( + &column.ident, + format!( + "`{0}` is the name of a method that `#[model(soft_deletes)]` generates; rename the field and \ + keep its column with `#[column(\"{0}\")]`", + column.ident.unraw() + ), + )); + } + } + let methods = quote! { + impl ::laravel::model::SoftDeletes for #name {} + + impl #name { + /// Whether the model's row is soft deleted. + #vis fn trashed(&self) -> bool { + ::laravel::model::__trashed(self) + } + + /// Clear the model's `deleted_at`, in both the database and this model. + /// + /// Runs the `restoring` hook and dispatches `Restored`. + #[track_caller] + #vis fn restore(&mut self) -> #future> + #send + '_ { + ::laravel::model::__restore(self) + } + + /// Remove the model's row from the database, instead of setting its `deleted_at`. + #[track_caller] + #vis fn force_delete(self) -> #future> + #send { + ::laravel::model::__force_delete(self) + } + } + }; + + Ok((meta, Some(methods))) +} + /// `BlogPost` as `blog_post`. pub(crate) fn snake_case(name: &str) -> String { let mut snake = String::with_capacity(name.len() + 4); diff --git a/src/model/mod.rs b/src/model/mod.rs index cde8c22b2..7802363fd 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, __stamp, __trashed, + __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, Restored, 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` field instead of removing the row, and queries leave out soft-deleted rows. Adds `trashed`, `restore`, and `force_delete`, and implements [`SoftDeletes`] | /// | `#[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..71a79a1ca --- /dev/null +++ b/tests/model_soft_deletes.rs @@ -0,0 +1,399 @@ +use std::sync::Mutex; + +use laravel::config::database::ConnectionConfig; +use laravel::container::Inject; +use laravel::db::{self, col}; +use laravel::event::Event; +use laravel::model::{BelongsTo, Deleted, HasMany, Hooks, Restored, create, model}; +use laravel::testing::prelude::*; +use laravel::time::Timestamp; + +#[model(soft_deletes)] +pub struct Author { + pub id: i64, + pub name: String, + pub created_at: Timestamp, + pub updated_at: Timestamp, + pub deleted_at: Option, + #[has_many] + pub posts: HasMany, +} + +#[model(soft_deletes, hooks)] +pub struct Post { + pub id: i64, + pub author_id: i64, + pub title: String, + pub locked: bool, + pub deleted_at: Option, + #[belongs_to] + pub author: BelongsTo, +} + +impl Hooks for Post { + async fn restoring(&self) -> laravel::Result<()> { + laravel::abort_if(self.locked, 409) + } +} + +#[derive(Default)] +struct Recorded(Mutex>); + +impl Recorded { + fn push(&self, event: String) { + self.0.lock().unwrap().push(event); + } + + 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 model = &event.model; + let trashed = model.trashed(); + let touched = if trashed && model.deleted_at == Some(model.updated_at) { + format!(" at {}", model.updated_at) + } else { + String::new() + }; + recorded.push(format!("deleted {} trashed={trashed}{touched}", model.name)); + }); + events.listen( + |event: Event>, recorded: Inject| async move { + recorded.push(format!("restored {}", event.model.name)); + }, + ); + }) + .create() +} + +async fn create_tables() -> laravel::Result<()> { + let connection = db::default_connection()?; + connection + .schema() + .create("authors", |table| { + table.id(); + table.string("name"); + table.timestamps(); + table.soft_deletes(); + }) + .await?; + connection + .schema() + .create("posts", |table| { + table.id(); + table.big_integer("author_id"); + table.string("title"); + table.boolean("locked"); + table.soft_deletes(); + }) + .await?; + + Ok(()) +} + +async fn author(name: &str) -> laravel::Result { + create!(Author { name }).await +} + +async fn post(author: &Author, title: &str) -> laravel::Result { + create!(Post { + author_id: author.id, + title, + locked: false, + }) + .await +} + +fn at(time: &str) -> Timestamp { + time.parse().unwrap() +} + +fn names(authors: &[Author]) -> Vec<&str> { + authors.iter().map(|author| author.name.as_str()).collect() +} + +#[tokio::test] +async fn delete_sets_deleted_at_and_queries_leave_the_row_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 taylor = author("Taylor").await?; + author("Abigail").await?; + assert!(!taylor.trashed()); + + app.travel_to(at("2026-12-01T10:00:00Z")); + taylor.delete().await?; + assert_eq!(recorded.take(), ["deleted Taylor trashed=true at 2026-12-01T10:00:00Z"]); + + assert_eq!(names(&Author::all().await?), ["Abigail"]); + assert!(Author::find(1).await?.is_none()); + assert_eq!(Author::query().count().await?, 1); + assert_eq!( + names(&Author::query().with_trashed().get().await?), + ["Taylor", "Abigail"] + ); + + let trashed = Author::query().only_trashed().get().await?; + assert_eq!(names(&trashed), ["Taylor"]); + assert_eq!(trashed[0].deleted_at, Some(at("2026-12-01T10:00:00Z"))); + assert_eq!( + trashed[0].updated_at, + at("2026-12-01T10:00:00Z"), + "the soft delete also touches `updated_at`" + ); + assert!(trashed[0].trashed()); + + let raw = db::table("authors").count().await?; + assert_eq!(raw, 2, "the row stays in the table"); + + Ok(()) + }) + .await +} + +#[tokio::test] +async fn restore_clears_deleted_at_after_the_restoring_hook() -> laravel::Result<()> { + let app = app(); + let recorded = app.resolve::().await; + + app.scope(async || { + create_tables().await?; + let taylor = author("Taylor").await?; + taylor.delete().await?; + recorded.take(); + + let mut taylor = Author::query().with_trashed().find_or_fail(1).await?; + app.travel_to(at("2026-12-02T09:00:00Z")); + taylor.restore().await?; + assert!(!taylor.trashed()); + assert_eq!( + taylor.updated_at, + at("2026-12-02T09:00:00Z"), + "the model gets the row's `updated_at`" + ); + assert_eq!(Author::find_or_fail(1).await?.updated_at, at("2026-12-02T09:00:00Z")); + assert_eq!(recorded.take(), ["restored Taylor"]); + assert_eq!(names(&Author::all().await?), ["Taylor"]); + + let locked = post(&taylor, "Locked").await?; + let id = locked.id; + db::table("posts") + .filter(col("id").eq(id)) + .update(db::values! { locked: true }) + .await?; + locked.delete().await?; + let mut locked = Post::query().only_trashed().find_or_fail(id).await?; + let error = locked.restore().await.unwrap_err(); + assert_eq!(error.status(), 409, "the `restoring` hook stops the restore"); + assert!(locked.trashed()); + assert_eq!(Post::query().only_trashed().count().await?, 1); + + Ok(()) + }) + .await +} + +#[tokio::test] +async fn force_delete_removes_the_row() -> laravel::Result<()> { + let app = app(); + let recorded = app.resolve::().await; + + app.scope(async || { + create_tables().await?; + let taylor = author("Taylor").await?; + taylor.delete().await?; + let taylor = Author::query().with_trashed().find_or_fail(1).await?; + recorded.take(); + + taylor.force_delete().await?; + let events = recorded.take(); + assert_eq!(events.len(), 1); + assert!(events[0].starts_with("deleted Taylor trashed=true"), "{events:?}"); + assert_eq!(Author::query().with_trashed().count().await?, 0); + assert_eq!(db::table("authors").count().await?, 0); + + Ok(()) + }) + .await +} + +#[tokio::test] +async fn query_writes_soft_delete_restore_and_force_delete() -> laravel::Result<()> { + let app = app(); + + app.scope(async || { + create_tables().await?; + for name in ["Taylor", "Abigail", "James", "Jess"] { + author(name).await?; + } + + let deleted = Author::query() + .filter(Author::name.is_in(["Taylor", "Abigail"])) + .delete() + .await?; + assert_eq!(deleted, 2); + assert_eq!(names(&Author::all().await?), ["James", "Jess"]); + assert_eq!( + Author::query().delete().await?, + 2, + "a second delete leaves out the rows it already trashed" + ); + assert_eq!(Author::query().with_trashed().count().await?, 4); + + let restored = Author::query().filter(Author::name.eq("Taylor")).restore().await?; + assert_eq!(restored, 1, "`restore` includes soft-deleted rows"); + assert_eq!(names(&Author::all().await?), ["Taylor"]); + + let removed = Author::query() + .filter(Author::name.is_in(["Taylor", "Abigail"])) + .force_delete() + .await?; + assert_eq!( + removed, 2, + "like Eloquent, `force_delete` also removes soft-deleted rows" + ); + assert_eq!(names(&Author::query().with_trashed().get().await?), ["James", "Jess"]); + assert_eq!(Author::query().force_delete().await?, 2); + assert_eq!(db::table("authors").count().await?, 0); + + Ok(()) + }) + .await +} + +#[tokio::test] +async fn relations_leave_out_soft_deleted_rows() -> laravel::Result<()> { + let app = app(); + + app.scope(async || { + create_tables().await?; + let taylor = author("Taylor").await?; + let abigail = author("Abigail").await?; + post(&taylor, "Kept").await?; + post(&taylor, "Trashed").await?.delete().await?; + post(&abigail, "Orphaned").await?.delete().await?; + + let titles: Vec = taylor.posts().get().await?.into_iter().map(|post| post.title).collect(); + assert_eq!(titles, ["Kept"]); + assert_eq!(taylor.posts().with_trashed().count().await?, 2); + + let authors = Author::query() + .with(Author::posts) + .with_count(Author::posts) + .get() + .await?; + assert_eq!(authors[0].posts.len(), 1); + assert_eq!(authors[1].posts.len(), 0); + + let with_posts = Author::query().has(Author::posts).get().await?; + assert_eq!(names(&with_posts), ["Taylor"]); + + let constrained = Author::query() + .with_count(Author::posts.query(|posts| posts.with_trashed())) + .get() + .await?; + assert_eq!(constrained[0].posts.count(), 2); + assert_eq!(constrained[1].posts.count(), 1); + + abigail.delete().await?; + let posts = Post::query().with(Post::author).get().await?; + assert_eq!(posts.len(), 1); + assert_eq!(posts[0].author.name, "Taylor"); + + Ok(()) + }) + .await +} + +#[tokio::test] +async fn the_scope_names_its_table_in_joins() -> laravel::Result<()> { + let app = app(); + + app.scope(async || { + create_tables().await?; + let taylor = author("Taylor").await?; + post(&taylor, "Kept").await?; + post(&taylor, "Trashed").await?.delete().await?; + + let posts = Post::query() + .join("authors", Author::id.eq(Post::author_id)) + .filter(Author::name.eq("Taylor")) + .get() + .await?; + assert_eq!(posts.len(), 1, "both tables have a `deleted_at` column"); + assert_eq!(posts[0].title, "Kept"); + + Ok(()) + }) + .await +} + +#[tokio::test] +async fn saving_and_refreshing_a_trashed_model_reach_its_row() -> laravel::Result<()> { + let app = app(); + + app.scope(async || { + create_tables().await?; + let taylor = author("Taylor").await?; + taylor.delete().await?; + let mut taylor = Author::query().with_trashed().find_or_fail(1).await?; + + laravel::model::update!(taylor { name: "Otwell" }).await?; + taylor.refresh().await?; + assert_eq!(taylor.name, "Otwell"); + assert!(taylor.trashed()); + assert!(taylor.fresh().await?.is_some()); + + Ok(()) + }) + .await +} + +#[tokio::test] +async fn trashed_rows_can_be_pruned_by_age() -> laravel::Result<()> { + use laravel::time::{Dates, ToSpan}; + + let app = app(); + app.travel_to(at("2026-10-01T09:00:00Z")); + + app.scope(async || { + create_tables().await?; + author("Old").await?.delete().await?; + app.travel_to(at("2026-11-25T09:00:00Z")); + author("Recent").await?.delete().await?; + author("Active").await?; + app.travel_to(at("2026-12-01T09:00:00Z")); + + let pruned = Author::query() + .only_trashed() + .filter(Author::deleted_at.lt(laravel::now().minus(30.days()).timestamp())) + .force_delete() + .await?; + assert_eq!(pruned, 1); + assert_eq!( + names(&Author::query().with_trashed().get().await?), + ["Recent", "Active"] + ); + + 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;