sea-orm-soft-delete 0.1.0

Soft deletes for SeaORM: trash, restore, prune, and queries that skip trashed rows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! Runs against an in-memory SQLite database, so the package needs no server to test.

// The hook overrides in this file are `async fn` to show how apps write them,
// even where a test hook has nothing to await.
#![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,
};

/// A plain soft-deletable table that also touches `updated_at` and forbids hard deletes.
#[allow(clippy::empty_enums)] // the test tables have no relations
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)
    }
}

/// A table whose hooks write to a log, keyed by slug so parallel tests do not mix.
#[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: &note::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: &note::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: &note::Model,
        _db: &C,
    ) -> Result<(), DbErr> {
        record(model, "after_soft_delete");
        Ok(())
    }

    async fn before_restore<C: ConnectionTrait>(model: &note::Model, _db: &C) -> Result<(), DbErr> {
        record(model, "before_restore");
        Ok(())
    }

    async fn after_restore<C: ConnectionTrait>(model: &note::Model, _db: &C) -> Result<(), DbErr> {
        record(model, "after_restore");
        Ok(())
    }

    async fn before_force_delete<C: ConnectionTrait>(
        model: &note::Model,
        _db: &C,
    ) -> Result<(), DbErr> {
        record(model, "before_force_delete");
        Ok(())
    }

    async fn after_force_delete<C: ConnectionTrait>(
        model: &note::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();
}

// Trash, restore, delete for good

#[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);
}

// Many rows

#[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"]
    );
}

// Pruning

#[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);
}

// Hooks

#[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);
}

// Partial unique index

#[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());
}