Skip to main content

sea_orm_soft_delete/
query.rs

1use sea_orm::{ColumnTrait, QueryFilter, Select};
2
3use crate::entity::SoftDelete;
4
5/// Trash filters for any query on a [`SoftDelete`] entity.
6///
7/// ```
8/// # mod posts {
9/// #     use sea_orm::entity::prelude::*;
10/// #     #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
11/// #     #[sea_orm(table_name = "posts")]
12/// #     pub struct Model {
13/// #         #[sea_orm(primary_key)]
14/// #         pub id: i32,
15/// #         pub category_id: i32,
16/// #         pub slug: String,
17/// #         pub deleted_at: Option<DateTimeWithTimeZone>,
18/// #     }
19/// #     #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
20/// #     pub enum Relation {}
21/// # }
22/// # impl sea_orm::ActiveModelBehavior for posts::ActiveModel {}
23/// # impl sea_orm_soft_delete::SoftDelete for posts::Entity {
24/// #     fn deleted_at_column() -> Self::Column { posts::Column::DeletedAt }
25/// # }
26/// use sea_orm::{ColumnTrait, DatabaseConnection, DbErr, EntityTrait, QueryFilter};
27/// use sea_orm_soft_delete::TrashedQuery;
28///
29/// async fn example(db: &DatabaseConnection) -> Result<(), DbErr> {
30///     let posts = posts::Entity::find()
31///         .filter(posts::Column::CategoryId.eq(1))
32///         .without_trashed()
33///         .all(db)
34///         .await?;
35///     Ok(())
36/// }
37/// # fn main() {}
38/// ```
39///
40/// There is no `with_trashed()`: a plain query already includes trashed rows.
41pub trait TrashedQuery {
42    /// Keeps only rows that are not in the trash.
43    #[must_use]
44    fn without_trashed(self) -> Self;
45
46    /// Keeps only rows that are in the trash.
47    #[must_use]
48    fn only_trashed(self) -> Self;
49}
50
51impl<E: SoftDelete> TrashedQuery for Select<E> {
52    fn without_trashed(self) -> Self {
53        self.filter(E::deleted_at_column().is_null())
54    }
55
56    fn only_trashed(self) -> Self {
57        self.filter(E::deleted_at_column().is_not_null())
58    }
59}