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
14 changes: 14 additions & 0 deletions crates/database/src/db/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,8 @@ pub struct Builder<M = ()> {
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<fn() -> M>,
}

Expand All @@ -182,6 +184,7 @@ impl<M> Clone for Builder<M> {
creates: self.creates.clone(),
timestamps: self.timestamps,
model_table: self.model_table,
trashed_scope: self.trashed_scope,
..self.retyped()
}
}
Expand Down Expand Up @@ -354,6 +357,7 @@ impl<M> Builder<M> {
creates: Creates::default(),
timestamps: Timestamps::default(),
model_table: None,
trashed_scope: false,
model: PhantomData,
}
}
Expand All @@ -370,6 +374,7 @@ impl<M> Builder<M> {
creates: Creates::default(),
timestamps: Timestamps::default(),
model_table: None,
trashed_scope: false,
model: PhantomData,
}
}
Expand All @@ -385,6 +390,7 @@ impl<M> Builder<M> {
creates: Creates::default(),
timestamps: Timestamps::default(),
model_table: None,
trashed_scope: false,
model: PhantomData,
}
}
Expand All @@ -393,9 +399,17 @@ impl<M> Builder<M> {
pub(crate) fn reading(&self, from: impl Into<Source>) -> 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))
Expand Down
35 changes: 35 additions & 0 deletions 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 @@ -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)]
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
/// `#[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 All @@ -197,6 +204,14 @@ pub struct Field<M> {
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<M> {
/// 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<Timestamp>),
}

/// A timestamp column of a [`Meta`], with a function that sets the column's value on a model.
pub struct Stamp<M> {
/// The column's name.
Expand Down Expand Up @@ -227,6 +242,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 All @@ -237,6 +253,20 @@ impl<M> fmt::Debug for Field<M> {
}
}

impl<M> Clone for SoftDelete<M> {
fn clone(&self) -> Self {
*self
}
}

impl<M> Copy for SoftDelete<M> {}

impl<M> fmt::Debug for SoftDelete<M> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.debug_tuple("SoftDelete").field(&self.name).finish()
}
}

impl<M> fmt::Debug for Stamp<M> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.debug_tuple("Stamp").field(&self.name).finish()
Expand All @@ -251,6 +281,11 @@ where
value.into()
}

#[doc(hidden)]
pub fn __soft_delete<T: From<Timestamp>>(deleted_at: Option<Timestamp>) -> Option<T> {
deleted_at.map(T::from)
}

#[doc(hidden)]
pub fn __stamp<T: From<Timestamp>>(now: Timestamp) -> T {
T::from(now)
Expand Down
7 changes: 7 additions & 0 deletions crates/database/src/model/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ 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);
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
}

Expand Down Expand Up @@ -116,8 +120,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 finds the model's row even when it's soft deleted.
pub fn query_of<M: Model>(model: &M) -> Builder<M> {
let mut query = __query::<M>();
query.without_trashed_scope();
if let Some(name) = &model.__connection().0 {
query.on = On::Named(name.to_string());
}
Expand Down
193 changes: 193 additions & 0 deletions crates/database/src/model/soft_delete.rs
Original file line number Diff line number Diff line change
@@ -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<M: SoftDeletes>() -> SoftDelete<M> {
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<M: Model>(deleted_at: SoftDelete<M>) -> 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<M: Model>(deleted_at: SoftDelete<M>, 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<M: Model>(deleted_at: SoftDelete<M>, now: Timestamp) -> Values {
let values = Values::new().set(deleted_at.name, None::<Timestamp>);
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<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 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<Timestamp> }
/// # 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::<M>()))
}

/// 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<Timestamp> }
/// # 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<Output = Result<u64>> + use<M> {
let location = self.call_site();
self.clone()
.called_at(location)
.only_trashed()
.update_values(restoring(column::<M>(), 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<Output = Result<u64>> + use<M> {
single_table(self.clone().called_at(self.call_site())).delete_rows()
}
}

impl<M: Model> Builder<M> {
/// 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<Output = Result<u64>> + use<M> {
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<M: Model>(mut model: M, force: bool, location: &'static Location<'static>) -> Result<u64> {
model.deleting().await?;
let query = query_of(&model).called_at(location).filter(key_is::<M>(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<M: SoftDeletes>(model: M) -> impl Future<Output = Result<()>> + Send {
let location = Location::caller();
async move {
delete(model, true, location).await?;
Ok(())
}
}

#[doc(hidden)]
#[track_caller]
pub fn __restore<M: SoftDeletes>(model: &mut M) -> impl Future<Output = Result<()>> + Send + '_ {
let location = Location::caller();
let now = crate::now().timestamp();
let deleted_at = column::<M>();
let write = query_of(model)
.called_at(location)
.filter(key_is::<M>(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(())
}
}
7 changes: 5 additions & 2 deletions crates/database/src/model/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,7 @@ 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`.
fn single_table<M: Model>(query: Builder<M>) -> Builder<M> {
pub(super) fn single_table<M: Model>(query: Builder<M>) -> Builder<M> {
let select = &query.select;
let filters_its_table = select.joins.is_empty()
&& !select.filter.iter().any(Condition::has_subquery)
Expand Down Expand Up @@ -592,6 +592,9 @@ impl<M: Model> Builder<M> {
/// 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]`
Expand All @@ -611,7 +614,7 @@ impl<M: Model> Builder<M> {
/// 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()
self.delete_or_trash()
}

/// Starts an update that adds `amount` to `column` in every row the query matches, as
Expand Down
Loading