sea_orm_soft_delete/model.rs
1use std::future::Future;
2
3use chrono::Utc;
4use sea_orm::{
5 ColumnTrait, ConnectionTrait, DbErr, DeleteResult, EntityTrait, FromQueryResult, ModelTrait,
6 QueryFilter,
7};
8
9use crate::{
10 entity::SoftDelete,
11 row::{primary_key_condition, reload, set_deleted_at},
12};
13
14/// Trash operations on one row. Every `Model` of a [`SoftDelete`] entity gets them.
15///
16/// ```
17/// # mod posts {
18/// # use sea_orm::entity::prelude::*;
19/// # #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
20/// # #[sea_orm(table_name = "posts")]
21/// # pub struct Model {
22/// # #[sea_orm(primary_key)]
23/// # pub id: i32,
24/// # pub category_id: i32,
25/// # pub slug: String,
26/// # pub deleted_at: Option<DateTimeWithTimeZone>,
27/// # }
28/// # #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
29/// # pub enum Relation {}
30/// # }
31/// # impl sea_orm::ActiveModelBehavior for posts::ActiveModel {}
32/// # impl sea_orm_soft_delete::SoftDelete for posts::Entity {
33/// # fn deleted_at_column() -> Self::Column { posts::Column::DeletedAt }
34/// # }
35/// use sea_orm::{DatabaseConnection, DbErr};
36/// use sea_orm_soft_delete::SoftDeleteModel;
37///
38/// async fn example(db: &DatabaseConnection, post: posts::Model) -> Result<(), DbErr> {
39/// let post = post.soft_delete(db).await?;
40/// assert!(post.is_trashed());
41/// let post = post.restore(db).await?;
42/// Ok(())
43/// }
44/// # fn main() {}
45/// ```
46///
47/// The plain methods run the entity's hooks ([`SoftDelete::before_soft_delete`]
48/// and friends); the `*_quietly` ones skip them.
49/// Pass a `DatabaseTransaction` as `db` to make hooks and the change atomic.
50pub trait SoftDeleteModel:
51 ModelTrait<Entity: SoftDelete<Model = Self>> + FromQueryResult + Send + Sync
52{
53 /// Whether the row is in the trash.
54 fn is_trashed(&self) -> bool {
55 self.get(<Self::Entity as SoftDelete>::deleted_at_column())
56 .is_some()
57 }
58
59 /// Moves the row to the trash and returns it as stored. A row already in the
60 /// trash, even if this copy of it is out of date, keeps its `deleted_at` and runs
61 /// no `after_soft_delete` hook.
62 ///
63 /// # Errors
64 ///
65 /// When a query fails, the row no longer exists, or a hook returns an error.
66 fn soft_delete<C: ConnectionTrait>(
67 self,
68 db: &C,
69 ) -> impl Future<Output = Result<Self, DbErr>> + Send {
70 async move {
71 if self.is_trashed() {
72 return Ok(self);
73 }
74 Self::Entity::before_soft_delete(&self, db).await?;
75 let (model, changed) = write_deleted_at(self, db, true).await?;
76 if changed {
77 Self::Entity::after_soft_delete(&model, db).await?;
78 }
79 Ok(model)
80 }
81 }
82
83 /// [`soft_delete`](Self::soft_delete) without hooks.
84 ///
85 /// # Errors
86 ///
87 /// When a query fails or the row no longer exists.
88 fn soft_delete_quietly<C: ConnectionTrait>(
89 self,
90 db: &C,
91 ) -> impl Future<Output = Result<Self, DbErr>> + Send {
92 async move {
93 if self.is_trashed() {
94 return Ok(self);
95 }
96 Ok(write_deleted_at(self, db, true).await?.0)
97 }
98 }
99
100 /// Takes the row out of the trash and returns it as stored. A row that is not
101 /// trashed, even if this copy of it is out of date, runs no `after_restore` hook.
102 ///
103 /// With [`unique_while_kept`](crate::unique_while_kept), restoring fails with a
104 /// unique violation when a kept row has taken the value meanwhile.
105 ///
106 /// # Errors
107 ///
108 /// When a query fails, the row no longer exists, or a hook returns an error.
109 fn restore<C: ConnectionTrait>(
110 self,
111 db: &C,
112 ) -> impl Future<Output = Result<Self, DbErr>> + Send {
113 async move {
114 if !self.is_trashed() {
115 return Ok(self);
116 }
117 Self::Entity::before_restore(&self, db).await?;
118 let (model, changed) = write_deleted_at(self, db, false).await?;
119 if changed {
120 Self::Entity::after_restore(&model, db).await?;
121 }
122 Ok(model)
123 }
124 }
125
126 /// [`restore`](Self::restore) without hooks.
127 ///
128 /// # Errors
129 ///
130 /// When a query fails or the row no longer exists.
131 fn restore_quietly<C: ConnectionTrait>(
132 self,
133 db: &C,
134 ) -> impl Future<Output = Result<Self, DbErr>> + Send {
135 async move {
136 if !self.is_trashed() {
137 return Ok(self);
138 }
139 Ok(write_deleted_at(self, db, false).await?.0)
140 }
141 }
142
143 /// Deletes the row for good, trashed or not. It bypasses `ActiveModelBehavior`,
144 /// so it still works when [`deny_hard_delete`](crate::deny_hard_delete) guards
145 /// the plain `delete`.
146 ///
147 /// # Errors
148 ///
149 /// When the query fails or a hook returns an error.
150 fn force_delete<C: ConnectionTrait>(
151 self,
152 db: &C,
153 ) -> impl Future<Output = Result<DeleteResult, DbErr>> + Send {
154 async move {
155 Self::Entity::before_force_delete(&self, db).await?;
156 let result = delete_row(&self, db).await?;
157 if result.rows_affected > 0 {
158 Self::Entity::after_force_delete(&self, db).await?;
159 }
160 Ok(result)
161 }
162 }
163
164 /// [`force_delete`](Self::force_delete) without hooks.
165 ///
166 /// # Errors
167 ///
168 /// When the query fails.
169 fn force_delete_quietly<C: ConnectionTrait>(
170 self,
171 db: &C,
172 ) -> impl Future<Output = Result<DeleteResult, DbErr>> + Send {
173 async move { delete_row(&self, db).await }
174 }
175}
176
177impl<M> SoftDeleteModel for M where
178 M: ModelTrait<Entity: SoftDelete<Model = M>> + FromQueryResult + Send + Sync
179{
180}
181
182/// Trashes or restores the row if it is still in the other state; returns it as
183/// stored and whether it changed. The state check is in the `UPDATE` itself, so an
184/// out-of-date copy cannot overwrite `deleted_at` or run the after-hook twice.
185async fn write_deleted_at<M, C>(model: M, db: &C, trashed: bool) -> Result<(M, bool), DbErr>
186where
187 M: SoftDeleteModel,
188 C: ConnectionTrait,
189{
190 let row = primary_key_condition(&model);
191 let column = <M::Entity as SoftDelete>::deleted_at_column();
192 let still_other_state = if trashed {
193 column.is_null()
194 } else {
195 column.is_not_null()
196 };
197 let result = set_deleted_at(M::Entity::update_many(), Utc::now(), trashed)
198 .filter(row.clone())
199 .filter(still_other_state)
200 .exec(db)
201 .await?;
202 Ok((reload(db, row).await?, result.rows_affected > 0))
203}
204
205async fn delete_row<M, C>(model: &M, db: &C) -> Result<DeleteResult, DbErr>
206where
207 M: SoftDeleteModel,
208 C: ConnectionTrait,
209{
210 M::Entity::delete_many()
211 .filter(primary_key_condition(model))
212 .exec(db)
213 .await
214}