Skip to content
Open
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
2 changes: 1 addition & 1 deletion crates/database/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion crates/database/src/db/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand Down
18 changes: 18 additions & 0 deletions crates/database/src/model/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,16 @@ pub trait Hooks: Sized + Send + Sync + 'static {
fn deleting(&self) -> impl Future<Output = Result<()>> + 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<Output = Result<()>> + Send {
async { Ok(()) }
}
}

/// The columns that a create is about to insert into a row of model `M`, which
Expand Down Expand Up @@ -397,6 +407,14 @@ pub struct Deleted<M> {
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<M> {
/// The restored model.
pub model: M,
}

tokio::task_local! {
static MUTED: ();
}
Expand Down
10 changes: 9 additions & 1 deletion crates/database/src/model/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ mod morph;
pub mod query;
mod queued;
mod relation;
mod soft_delete;
mod update;
#[doc(hidden)]
pub mod write;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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};
Expand Down Expand Up @@ -174,6 +178,9 @@ pub struct Meta<M: Model> {
pub created_at: Option<Stamp<M>>,
/// The column that holds when the row last changed, if the model has one.
pub updated_at: Option<Stamp<M>>,
/// The column that holds when the row was soft deleted, if the model is declared with
/// `#[model(soft_deletes)]`.
pub deleted_at: Option<SoftDelete<M>>,
/// 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),
Expand Down Expand Up @@ -227,6 +234,7 @@ impl<M: Model> fmt::Debug for Meta<M> {
.field("columns", &self.columns)
.field("created_at", &self.created_at)
.field("updated_at", &self.updated_at)
.field("deleted_at", &self.deleted_at)
.finish()
}
}
Expand Down
7 changes: 5 additions & 2 deletions crates/database/src/model/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub fn __query<M: Model>() -> Builder<M> {
let mut query = Builder::new(on::<M>(), Source::from(M::META.table));
query.timestamps = Timestamps::of::<M>();
query.model_table = Some(M::META.table);
query
super::soft_delete::scoped(query)
}

/// Returns the connection that queries of `M` run on.
Expand Down Expand Up @@ -116,8 +116,11 @@ pub(crate) fn table_of<M: Model>() -> 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<M: Model>(model: &M) -> Builder<M> {
let mut query = __query::<M>();
let mut query = super::soft_delete::unscoped(__query::<M>());
if let Some(name) = &model.__connection().0 {
query.on = On::Named(name.to_string());
}
Expand Down
222 changes: 222 additions & 0 deletions crates/database/src/model/soft_delete.rs
Original file line number Diff line number Diff line change
@@ -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<M> {
/// 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<Timestamp>),
/// Whether the model's field holds a time.
pub trashed: fn(&M) -> bool,
}

impl<M> std::fmt::Debug for SoftDelete<M> {
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<Timestamp>` 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<M: Model>(soft: &SoftDelete<M>) -> 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<M: Model>(query: Builder<M>) -> Builder<M> {
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<M>(mut query: Builder<M>) -> Builder<M> {
query.select.filter.retain(|condition| !is_scope(condition));
query
}

fn is_scope(condition: &Condition) -> bool {
matches!(&condition.0, ConditionKind::Typed(_, marker) if (**marker).is::<Scope>())
}

/// Query methods of a model declared with `#[model(soft_deletes)]`.
impl<M: SoftDeletes> Builder<M> {
/// 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<Timestamp> }
/// # 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<Timestamp> }
/// # 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<Timestamp> }
/// # 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<Output = Result<u64>> + use<M> {
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::<Timestamp>))
}

/// 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<Output = Result<u64>> + use<M> {
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<M: Model>(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<M: Model>(model: &mut M) -> impl Future<Output = Result<()>> + 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::<M>(key_of(model)))
.update_values(touched::<M>(Values::new().set(soft.name, None::<Timestamp>), 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<M: Model>(model: &mut M, location: &'static Location<'static>) -> Result<u64> {
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::<M>(key_of(model)))
.update_values(touched::<M>(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<M: Model>(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<M: Model>(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<M: Model>(model: M) -> impl Future<Output = Result<()>> + Send {
let location = Location::caller();
async move {
model.deleting().await?;
let query = query_of(&model).called_at(location).filter(key_is::<M>(key_of(&model)));
super::update::delete_rows(query).await?;
fire(Deleted { model }).await
}
}
21 changes: 20 additions & 1 deletion crates/database/src/model/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,11 @@ impl<M: Model> std::fmt::Debug for MassUpdateBuilder<M> {
/// 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<M: Model>(query: Builder<M>) -> impl Future<Output = Result<u64>> + use<M> {
single_table(query).delete_rows()
}

fn single_table<M: Model>(query: Builder<M>) -> Builder<M> {
let select = &query.select;
let filters_its_table = select.joins.is_empty()
Expand Down Expand Up @@ -606,12 +611,26 @@ impl<M: Model> Builder<M> {
/// # 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<Output = Result<u64>> + use<M> {
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
Expand Down
Loading