#![allow(clippy::unused_async_trait_impl)]
use std::sync::Mutex;
use chrono::{Duration, Utc};
use sea_orm::{
entity::prelude::*, sea_query::Expr, ActiveValue::Set, Condition, Database, DatabaseConnection,
Schema,
};
use sea_orm_soft_delete::{
deny_hard_delete, unique_while_kept, SoftDelete, SoftDeleteModel, TrashedQuery,
};
#[allow(clippy::empty_enums)] mod post {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "posts")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub slug: String,
pub updated_at: Option<DateTimeWithTimeZone>,
pub deleted_at: Option<DateTimeWithTimeZone>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
}
#[async_trait::async_trait]
impl ActiveModelBehavior for post::ActiveModel {
async fn before_delete<C: ConnectionTrait>(self, _db: &C) -> Result<Self, DbErr> {
deny_hard_delete()?;
Ok(self)
}
}
impl SoftDelete for post::Entity {
fn deleted_at_column() -> Self::Column {
post::Column::DeletedAt
}
fn updated_at_column() -> Option<Self::Column> {
Some(post::Column::UpdatedAt)
}
}
#[allow(clippy::empty_enums)]
mod note {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "notes")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub slug: String,
pub deleted_at: Option<DateTimeWithTimeZone>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
static LOG: Mutex<Vec<String>> = Mutex::new(Vec::new());
fn record(model: ¬e::Model, event: &str) {
LOG.lock().unwrap().push(format!("{}:{event}", model.slug));
}
fn events(slug: &str) -> Vec<String> {
let prefix = format!("{slug}:");
LOG.lock()
.unwrap()
.iter()
.filter_map(|line| line.strip_prefix(&prefix).map(str::to_string))
.collect()
}
impl SoftDelete for note::Entity {
fn deleted_at_column() -> Self::Column {
note::Column::DeletedAt
}
async fn before_soft_delete<C: ConnectionTrait>(
model: ¬e::Model,
_db: &C,
) -> Result<(), DbErr> {
record(model, "before_soft_delete");
if model.slug.starts_with("locked") {
return Err(DbErr::Custom("locked notes stay".to_string()));
}
Ok(())
}
async fn after_soft_delete<C: ConnectionTrait>(
model: ¬e::Model,
_db: &C,
) -> Result<(), DbErr> {
record(model, "after_soft_delete");
Ok(())
}
async fn before_restore<C: ConnectionTrait>(model: ¬e::Model, _db: &C) -> Result<(), DbErr> {
record(model, "before_restore");
Ok(())
}
async fn after_restore<C: ConnectionTrait>(model: ¬e::Model, _db: &C) -> Result<(), DbErr> {
record(model, "after_restore");
Ok(())
}
async fn before_force_delete<C: ConnectionTrait>(
model: ¬e::Model,
_db: &C,
) -> Result<(), DbErr> {
record(model, "before_force_delete");
Ok(())
}
async fn after_force_delete<C: ConnectionTrait>(
model: ¬e::Model,
_db: &C,
) -> Result<(), DbErr> {
record(model, "after_force_delete");
Ok(())
}
}
async fn db() -> DatabaseConnection {
let db = Database::connect("sqlite::memory:").await.unwrap();
let schema = Schema::new(db.get_database_backend());
db.execute(&schema.create_table_from_entity(post::Entity))
.await
.unwrap();
db.execute(&schema.create_table_from_entity(note::Entity))
.await
.unwrap();
db.execute(&unique_while_kept(
"posts_slug_kept",
post::Entity,
[post::Column::Slug],
post::Column::DeletedAt,
))
.await
.unwrap();
db
}
async fn create(db: &DatabaseConnection, slug: &str) -> post::Model {
post::ActiveModel {
slug: Set(slug.to_string()),
..Default::default()
}
.insert(db)
.await
.unwrap()
}
async fn create_note(db: &DatabaseConnection, slug: &str) -> note::Model {
note::ActiveModel {
slug: Set(slug.to_string()),
..Default::default()
}
.insert(db)
.await
.unwrap()
}
async fn slugs(query: Select<post::Entity>, db: &DatabaseConnection) -> Vec<String> {
query
.all(db)
.await
.unwrap()
.into_iter()
.map(|post| post.slug)
.collect()
}
async fn age(db: &DatabaseConnection, slug: &str, days: i64) {
post::Entity::update_many()
.col_expr(
post::Column::DeletedAt,
Expr::value(Utc::now() - Duration::days(days)),
)
.filter(post::Column::Slug.eq(slug))
.exec(db)
.await
.unwrap();
}
#[tokio::test]
async fn soft_delete_hides_the_row_from_kept_queries() {
let db = db().await;
create(&db, "kept").await;
let trashed = create(&db, "trashed").await.soft_delete(&db).await.unwrap();
assert!(trashed.is_trashed());
assert_eq!(
slugs(post::Entity::find_without_trashed(), &db).await,
["kept"]
);
assert_eq!(
slugs(post::Entity::find_only_trashed(), &db).await,
["trashed"]
);
assert_eq!(slugs(post::Entity::find(), &db).await, ["kept", "trashed"]);
}
#[tokio::test]
async fn filters_combine_with_other_conditions() {
let db = db().await;
let kept = create(&db, "a").await;
let trashed = create(&db, "b").await.soft_delete(&db).await.unwrap();
let query = post::Entity::find()
.filter(post::Column::Slug.is_in(["a", "b"]))
.without_trashed();
let by_id = post::Entity::find_by_id(trashed.id).without_trashed();
assert_eq!(slugs(query, &db).await, ["a"]);
assert!(by_id.one(&db).await.unwrap().is_none());
assert_eq!(
post::Entity::find_by_id(kept.id)
.without_trashed()
.one(&db)
.await
.unwrap(),
Some(kept)
);
}
#[tokio::test]
async fn restore_brings_the_row_back() {
let db = db().await;
let post = create(&db, "hello").await.soft_delete(&db).await.unwrap();
let post = post.restore(&db).await.unwrap();
assert!(!post.is_trashed());
assert_eq!(
slugs(post::Entity::find_without_trashed(), &db).await,
["hello"]
);
}
#[tokio::test]
async fn trashing_twice_keeps_the_first_timestamp() {
let db = db().await;
let first = create(&db, "hello").await.soft_delete(&db).await.unwrap();
let second = first.clone().soft_delete(&db).await.unwrap();
assert_eq!(first.deleted_at, second.deleted_at);
}
#[tokio::test]
async fn trash_and_restore_touch_updated_at() {
let db = db().await;
let created = create(&db, "hello").await;
assert!(created.updated_at.is_none());
let trashed = created.soft_delete(&db).await.unwrap();
assert!(trashed.updated_at.is_some());
let restored = trashed.clone().restore(&db).await.unwrap();
assert!(restored.updated_at >= trashed.updated_at);
}
#[tokio::test]
async fn plain_delete_is_denied_but_force_delete_works() {
let db = db().await;
let post = create(&db, "hello").await;
let denied = post.clone().delete(&db).await.unwrap_err();
assert!(
denied.to_string().contains("hard delete is disabled"),
"{denied}"
);
let result = post.force_delete(&db).await.unwrap();
assert_eq!(result.rows_affected, 1);
assert_eq!(post::Entity::find().count(&db).await.unwrap(), 0);
}
#[tokio::test]
async fn trashes_and_restores_many_rows() {
let db = db().await;
for slug in ["a", "b", "c"] {
create(&db, slug).await;
}
let ab = Condition::all().add(post::Column::Slug.is_in(["a", "b"]));
let trashed = post::Entity::soft_delete_many(&db, ab.clone())
.await
.unwrap();
let again = post::Entity::soft_delete_many(&db, ab.clone())
.await
.unwrap();
assert_eq!((trashed, again), (2, 0));
assert_eq!(
slugs(post::Entity::find_without_trashed(), &db).await,
["c"]
);
let restored = post::Entity::restore_many(&db, ab).await.unwrap();
assert_eq!(restored, 2);
assert_eq!(
slugs(post::Entity::find_without_trashed(), &db).await,
["a", "b", "c"]
);
}
#[tokio::test]
async fn counts_and_prunes_only_rows_trashed_long_ago() {
let db = db().await;
create(&db, "kept").await;
create(&db, "recent").await.soft_delete(&db).await.unwrap();
create(&db, "old").await.soft_delete(&db).await.unwrap();
age(&db, "old", 40).await;
let prunable = post::Entity::count_prunable(&db, Duration::days(30))
.await
.unwrap();
let pruned = post::Entity::prune_trashed(&db, Duration::days(30))
.await
.unwrap();
assert_eq!((prunable, pruned), (1, 1));
assert_eq!(slugs(post::Entity::find(), &db).await, ["kept", "recent"]);
}
#[tokio::test]
async fn mass_prune_deletes_in_one_query() {
let db = db().await;
for slug in ["old-1", "old-2"] {
create(&db, slug).await.soft_delete(&db).await.unwrap();
age(&db, slug, 40).await;
}
let pruned = post::Entity::mass_prune_trashed(&db, Duration::days(30))
.await
.unwrap();
assert_eq!(pruned, 2);
assert_eq!(post::Entity::find().count(&db).await.unwrap(), 0);
}
#[tokio::test]
async fn hooks_run_around_each_operation() {
let db = db().await;
let note = create_note(&db, "hooked").await;
let note = note.soft_delete(&db).await.unwrap();
let note = note.restore(&db).await.unwrap();
note.force_delete(&db).await.unwrap();
assert_eq!(
events("hooked"),
[
"before_soft_delete",
"after_soft_delete",
"before_restore",
"after_restore",
"before_force_delete",
"after_force_delete",
]
);
}
#[tokio::test]
async fn a_before_hook_can_cancel() {
let db = db().await;
let note = create_note(&db, "locked").await;
let error = note.soft_delete(&db).await.unwrap_err();
assert!(error.to_string().contains("locked notes stay"), "{error}");
assert_eq!(events("locked"), ["before_soft_delete"]);
assert_eq!(
note::Entity::find_without_trashed()
.count(&db)
.await
.unwrap(),
1
);
}
#[tokio::test]
async fn quiet_methods_skip_hooks() {
let db = db().await;
let note = create_note(&db, "quiet").await;
let note = note.soft_delete_quietly(&db).await.unwrap();
assert!(note.is_trashed());
let note = note.restore_quietly(&db).await.unwrap();
assert!(!note.is_trashed());
note.force_delete_quietly(&db).await.unwrap();
assert_eq!(events("quiet"), Vec::<String>::new());
assert_eq!(note::Entity::find().count(&db).await.unwrap(), 0);
}
#[tokio::test]
async fn pruning_runs_force_delete_hooks_but_mass_pruning_does_not() {
let db = db().await;
for slug in ["pruned-one", "pruned-mass"] {
create_note(&db, slug)
.await
.soft_delete_quietly(&db)
.await
.unwrap();
}
note::Entity::update_many()
.col_expr(
note::Column::DeletedAt,
Expr::value(Utc::now() - Duration::days(40)),
)
.filter(note::Column::Slug.eq("pruned-one"))
.exec(&db)
.await
.unwrap();
note::Entity::prune_trashed(&db, Duration::days(30))
.await
.unwrap();
note::Entity::mass_prune_trashed(&db, Duration::zero())
.await
.unwrap();
assert_eq!(
events("pruned-one"),
["before_force_delete", "after_force_delete"]
);
assert_eq!(events("pruned-mass"), Vec::<String>::new());
assert_eq!(note::Entity::find().count(&db).await.unwrap(), 0);
}
#[tokio::test]
async fn a_trashed_slug_can_be_used_again() {
let db = db().await;
create(&db, "hello").await.soft_delete(&db).await.unwrap();
create(&db, "hello").await;
assert_eq!(slugs(post::Entity::find(), &db).await, ["hello", "hello"]);
}
#[tokio::test]
async fn two_kept_rows_cannot_share_a_slug() {
let db = db().await;
create(&db, "hello").await;
let duplicate = post::ActiveModel {
slug: Set("hello".to_string()),
..Default::default()
}
.insert(&db)
.await;
assert!(duplicate.is_err());
}