lemmy_db_schema 1.0.0-beta.0

A link aggregator for the fediverse
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
use crate::{
  diesel::{DecoratableTarget, OptionalExtension},
  newtypes::{CommentId, CommunityId, PostId},
  source::comment::{
    Comment,
    CommentActions,
    CommentInsertForm,
    CommentLikeForm,
    CommentSavedForm,
    CommentUpdateForm,
  },
  traits::{Likeable, Saveable},
  utils::DELETED_REPLACEMENT_TEXT,
};
use chrono::{DateTime, Utc};
use diesel::{
  ExpressionMethods,
  JoinOnDsl,
  QueryDsl,
  dsl::{insert_into, not},
  expression::SelectableHelper,
  update,
};
use diesel_async::RunQueryDsl;
use diesel_ltree::{Ltree, dsl::LtreeExtensions};
use diesel_uplete::{UpleteCount, uplete};
use lemmy_db_schema_file::{
  InstanceId,
  PersonId,
  schema::{comment, comment_actions, community, post},
};
use lemmy_diesel_utils::{
  connection::{DbPool, get_conn},
  dburl::DbUrl,
  traits::Crud,
  utils::functions::{coalesce, hot_rank},
};
use lemmy_utils::{
  error::{LemmyErrorExt, LemmyErrorType, LemmyResult, UntranslatedError},
  settings::structs::Settings,
};
use url::Url;

impl Comment {
  pub async fn permadelete_for_creator(
    pool: &mut DbPool<'_>,
    creator_id: PersonId,
  ) -> LemmyResult<Vec<Self>> {
    let conn = &mut get_conn(pool).await?;

    diesel::update(comment::table.filter(comment::creator_id.eq(creator_id)))
      .set((
        comment::content.eq(DELETED_REPLACEMENT_TEXT),
        comment::deleted.eq(true),
        comment::updated_at.eq(Utc::now()),
      ))
      .get_results::<Self>(conn)
      .await
      .with_lemmy_type(LemmyErrorType::CouldntUpdate)
  }

  pub async fn update_removed_for_creator(
    pool: &mut DbPool<'_>,
    creator_id: PersonId,
    removed: bool,
  ) -> LemmyResult<Vec<Comment>> {
    let conn = &mut get_conn(pool).await?;
    diesel::update(comment::table.filter(comment::creator_id.eq(creator_id)))
      .set((
        comment::removed.eq(removed),
        comment::updated_at.eq(Utc::now()),
      ))
      .get_results(conn)
      .await
      .with_lemmy_type(LemmyErrorType::CouldntUpdate)
  }

  /// Diesel can't update from join unfortunately, so you'll need to loop over these
  async fn creator_comments_in_community(
    pool: &mut DbPool<'_>,
    creator_id: PersonId,
    community_id: CommunityId,
  ) -> LemmyResult<Vec<Self>> {
    let conn = &mut get_conn(pool).await?;

    comment::table
      .inner_join(post::table)
      .filter(comment::creator_id.eq(creator_id))
      .filter(post::community_id.eq(community_id))
      .select(Self::as_select())
      .load::<Self>(conn)
      .await
      .with_lemmy_type(LemmyErrorType::NotFound)
  }

  /// Diesel can't update from join unfortunately, so you'll need to loop over these
  async fn creator_comments_in_instance(
    pool: &mut DbPool<'_>,
    creator_id: PersonId,
    instance_id: InstanceId,
  ) -> LemmyResult<Vec<Self>> {
    let conn = &mut get_conn(pool).await?;
    let community_join = community::table.on(post::community_id.eq(community::id));

    comment::table
      .inner_join(post::table)
      .inner_join(community_join)
      .filter(comment::creator_id.eq(creator_id))
      .filter(community::instance_id.eq(instance_id))
      .select(Self::as_select())
      .load::<Self>(conn)
      .await
      .with_lemmy_type(LemmyErrorType::NotFound)
  }

  pub async fn update_removed_for_creator_and_community(
    pool: &mut DbPool<'_>,
    creator_id: PersonId,
    community_id: CommunityId,
    removed: bool,
  ) -> LemmyResult<Vec<Self>> {
    let comments = Self::creator_comments_in_community(pool, creator_id, community_id).await?;
    let comment_ids: Vec<_> = comments.iter().map(|c| c.id).collect();

    let conn = &mut get_conn(pool).await?;

    update(comment::table)
      .filter(comment::id.eq_any(comment_ids))
      .set((
        comment::removed.eq(removed),
        comment::updated_at.eq(Utc::now()),
      ))
      .execute(conn)
      .await?;

    Ok(comments)
  }

  pub async fn update_removed_for_creator_and_instance(
    pool: &mut DbPool<'_>,
    creator_id: PersonId,
    instance_id: InstanceId,
    removed: bool,
  ) -> LemmyResult<Vec<Self>> {
    let comments = Self::creator_comments_in_instance(pool, creator_id, instance_id).await?;
    let comment_ids: Vec<_> = comments.iter().map(|c| c.id).collect();
    let conn = &mut get_conn(pool).await?;

    update(comment::table)
      .filter(comment::id.eq_any(comment_ids))
      .set((
        comment::removed.eq(removed),
        comment::updated_at.eq(Utc::now()),
      ))
      .execute(conn)
      .await?;
    Ok(comments)
  }

  #[expect(clippy::same_name_method)]
  pub async fn create(
    pool: &mut DbPool<'_>,
    comment_form: &CommentInsertForm,
    parent_path: Option<&Ltree>,
  ) -> LemmyResult<Comment> {
    Self::insert_apub(pool, None, comment_form, parent_path).await
  }

  pub async fn insert_apub(
    pool: &mut DbPool<'_>,
    timestamp: Option<DateTime<Utc>>,
    comment_form: &CommentInsertForm,
    parent_path: Option<&Ltree>,
  ) -> LemmyResult<Comment> {
    let conn = &mut get_conn(pool).await?;
    let comment_form = (comment_form, parent_path.map(|p| comment::path.eq(p)));

    if let Some(timestamp) = timestamp {
      insert_into(comment::table)
        .values(comment_form)
        .on_conflict(comment::ap_id)
        .filter_target(coalesce(comment::updated_at, comment::published_at).lt(timestamp))
        .do_update()
        .set(comment_form)
        .get_result::<Self>(conn)
        .await
    } else {
      insert_into(comment::table)
        .values(comment_form)
        .get_result::<Self>(conn)
        .await
    }
    .with_lemmy_type(LemmyErrorType::CouldntCreate)
  }

  pub async fn read_from_apub_id(
    pool: &mut DbPool<'_>,
    object_id: DbUrl,
  ) -> LemmyResult<Option<Self>> {
    let conn = &mut get_conn(pool).await?;
    comment::table
      .filter(comment::ap_id.eq(object_id))
      .first(conn)
      .await
      .optional()
      .with_lemmy_type(LemmyErrorType::NotFound)
  }

  pub fn parent_comment_id(&self) -> Option<CommentId> {
    let mut ltree_split: Vec<&str> = self.path.0.split('.').collect();
    ltree_split.remove(0); // The first is always 0
    if ltree_split.len() > 1 {
      let parent_comment_id = ltree_split.get(ltree_split.len() - 2);
      let p = parent_comment_id?;
      p.parse::<i32>().map(CommentId).ok()
    } else {
      None
    }
  }
  pub async fn update_hot_rank(pool: &mut DbPool<'_>, comment_id: CommentId) -> LemmyResult<Self> {
    let conn = &mut get_conn(pool).await?;

    diesel::update(comment::table.find(comment_id))
      .set(comment::hot_rank.eq(hot_rank(comment::score, comment::published_at)))
      .get_result::<Self>(conn)
      .await
      .with_lemmy_type(LemmyErrorType::CouldntUpdate)
  }
  pub fn local_url(&self, settings: &Settings) -> LemmyResult<Url> {
    let domain = settings.get_protocol_and_hostname();
    Ok(Url::parse(&format!("{domain}/comment/{}", self.id))?)
  }

  /// The comment was created locally and sent back, indicating that the community accepted it
  pub async fn set_not_pending(&self, pool: &mut DbPool<'_>) -> LemmyResult<()> {
    if self.local && self.federation_pending {
      let form = CommentUpdateForm {
        federation_pending: Some(false),
        ..Default::default()
      };
      Comment::update(pool, self.id, &form).await?;
    }
    Ok(())
  }

  /// Updates the locked field for a comment and all its children.
  pub async fn update_locked_for_comment_and_children(
    pool: &mut DbPool<'_>,
    comment_path: &Ltree,
    locked: bool,
  ) -> LemmyResult<Vec<Self>> {
    let form = CommentUpdateForm {
      locked: Some(locked),
      ..Default::default()
    };
    Self::update_comment_and_children(pool, comment_path, &form).await
  }

  /// Updates the removed field for a comment and all its children.
  pub async fn update_removed_for_comment_and_children(
    pool: &mut DbPool<'_>,
    comment_path: &Ltree,
    removed: bool,
  ) -> LemmyResult<Vec<Self>> {
    let form = CommentUpdateForm {
      removed: Some(removed),
      ..Default::default()
    };
    Self::update_comment_and_children(pool, comment_path, &form).await
  }

  /// A helper function to update comment and all its children.
  ///
  /// Don't expose so as to make sure you aren't overwriting data.
  async fn update_comment_and_children(
    pool: &mut DbPool<'_>,
    comment_path: &Ltree,
    form: &CommentUpdateForm,
  ) -> LemmyResult<Vec<Self>> {
    let conn = &mut get_conn(pool).await?;
    diesel::update(comment::table)
      .filter(comment::path.contained_by(comment_path))
      .set(form)
      .get_results(conn)
      .await
      .with_lemmy_type(LemmyErrorType::CouldntUpdate)
  }

  /// Update the remove field for all the comments under a post.
  pub async fn update_removed_for_post(
    pool: &mut DbPool<'_>,
    post_id: PostId,
    removed: bool,
  ) -> LemmyResult<Vec<Self>> {
    let conn = &mut get_conn(pool).await?;
    diesel::update(comment::table)
      .filter(comment::post_id.eq(post_id))
      .set((
        comment::removed.eq(removed),
        comment::updated_at.eq(Utc::now()),
      ))
      .get_results(conn)
      .await
      .with_lemmy_type(LemmyErrorType::CouldntUpdate)
  }

  pub async fn read_ap_ids_for_post(
    post_id: PostId,
    pool: &mut DbPool<'_>,
  ) -> LemmyResult<Vec<DbUrl>> {
    let conn = &mut get_conn(pool).await?;
    comment::table
      .filter(comment::post_id.eq(post_id))
      .filter(not(comment::deleted))
      .filter(not(comment::removed))
      .filter(not(comment::federation_pending))
      .order_by(comment::id)
      .select(comment::ap_id)
      .get_results(conn)
      .await
      .with_lemmy_type(LemmyErrorType::NotFound)
  }
}

impl Crud for Comment {
  type InsertForm = CommentInsertForm;
  type UpdateForm = CommentUpdateForm;
  type IdType = CommentId;

  /// Use [[Comment::create]]
  async fn create(_pool: &mut DbPool<'_>, _comment_form: &Self::InsertForm) -> LemmyResult<Self> {
    Err(UntranslatedError::Unreachable.into())
  }

  async fn update(
    pool: &mut DbPool<'_>,
    comment_id: CommentId,
    comment_form: &Self::UpdateForm,
  ) -> LemmyResult<Self> {
    let conn = &mut get_conn(pool).await?;
    diesel::update(comment::table.find(comment_id))
      .set(comment_form)
      .get_result::<Self>(conn)
      .await
      .with_lemmy_type(LemmyErrorType::CouldntUpdate)
  }
}

impl Likeable for CommentActions {
  type Form = CommentLikeForm;
  type IdType = CommentId;

  async fn like(pool: &mut DbPool<'_>, form: &Self::Form) -> LemmyResult<Self> {
    let conn = &mut get_conn(pool).await?;

    insert_into(comment_actions::table)
      .values(form)
      .on_conflict((comment_actions::comment_id, comment_actions::person_id))
      .do_update()
      .set(form)
      .returning(Self::as_select())
      .get_result::<Self>(conn)
      .await
      .with_lemmy_type(LemmyErrorType::CouldntCreate)
  }

  async fn remove_all_likes(
    pool: &mut DbPool<'_>,
    creator_id: PersonId,
  ) -> LemmyResult<UpleteCount> {
    let conn = &mut get_conn(pool).await?;

    uplete(comment_actions::table.filter(comment_actions::person_id.eq(creator_id)))
      .set_null(comment_actions::vote_is_upvote)
      .set_null(comment_actions::voted_at)
      .get_result(conn)
      .await
      .with_lemmy_type(LemmyErrorType::CouldntUpdate)
  }

  async fn remove_likes_in_community(
    pool: &mut DbPool<'_>,
    creator_id: PersonId,
    community_id: CommunityId,
  ) -> LemmyResult<UpleteCount> {
    let comments = Comment::creator_comments_in_community(pool, creator_id, community_id).await?;
    let comment_ids: Vec<_> = comments.iter().map(|c| c.id).collect();

    let conn = &mut get_conn(pool).await?;

    uplete(comment_actions::table.filter(comment_actions::comment_id.eq_any(comment_ids.clone())))
      .set_null(comment_actions::vote_is_upvote)
      .set_null(comment_actions::voted_at)
      .get_result(conn)
      .await
      .with_lemmy_type(LemmyErrorType::CouldntUpdate)
  }
}

impl Saveable for CommentActions {
  type Form = CommentSavedForm;
  async fn save(pool: &mut DbPool<'_>, form: &Self::Form) -> LemmyResult<Self> {
    let conn = &mut get_conn(pool).await?;
    insert_into(comment_actions::table)
      .values(form)
      .on_conflict((comment_actions::comment_id, comment_actions::person_id))
      .do_update()
      .set(form)
      .returning(Self::as_select())
      .get_result::<Self>(conn)
      .await
      .with_lemmy_type(LemmyErrorType::CouldntCreate)
  }
  async fn unsave(pool: &mut DbPool<'_>, form: &Self::Form) -> LemmyResult<UpleteCount> {
    let conn = &mut get_conn(pool).await?;
    uplete(comment_actions::table.find((form.person_id, form.comment_id)))
      .set_null(comment_actions::saved_at)
      .get_result(conn)
      .await
      .with_lemmy_type(LemmyErrorType::CouldntUpdate)
  }
}

impl CommentActions {
  pub async fn read(
    pool: &mut DbPool<'_>,
    comment_id: CommentId,
    person_id: PersonId,
  ) -> LemmyResult<Self> {
    let conn = &mut get_conn(pool).await?;
    comment_actions::table
      .find((person_id, comment_id))
      .select(Self::as_select())
      .first(conn)
      .await
      .with_lemmy_type(LemmyErrorType::NotFound)
  }
}

#[cfg(test)]
mod tests {

  use super::*;
  use crate::{
    newtypes::LanguageId,
    source::{
      community::{Community, CommunityInsertForm},
      instance::Instance,
      person::{Person, PersonInsertForm},
      post::{Post, PostInsertForm},
    },
    traits::{Likeable, Saveable},
    utils::RANK_DEFAULT,
  };
  use diesel_ltree::Ltree;
  use lemmy_diesel_utils::{connection::build_db_pool_for_tests, traits::Crud};
  use lemmy_utils::error::LemmyResult;
  use pretty_assertions::assert_eq;
  use serial_test::serial;
  use url::Url;

  #[tokio::test]
  #[serial]
  async fn test_crud() -> LemmyResult<()> {
    let pool = &build_db_pool_for_tests();
    let pool = &mut pool.into();

    let inserted_instance = Instance::read_or_create(pool, "my_domain.tld").await?;

    let new_person = PersonInsertForm::test_form(inserted_instance.id, "terry");

    let inserted_person = Person::create(pool, &new_person).await?;

    let new_community = CommunityInsertForm::new(
      inserted_instance.id,
      "test community".to_string(),
      "nada".to_owned(),
      "pubkey".to_string(),
    );
    let inserted_community = Community::create(pool, &new_community).await?;

    let new_post = PostInsertForm::new(
      "A test post".into(),
      inserted_person.id,
      inserted_community.id,
    );
    let inserted_post = Post::create(pool, &new_post).await?;

    let comment_form = CommentInsertForm::new(
      inserted_person.id,
      inserted_post.id,
      inserted_community.id,
      "A test comment".into(),
    );
    let inserted_comment = Comment::create(pool, &comment_form, None).await?;

    let expected_comment = Comment {
      id: inserted_comment.id,
      content: "A test comment".into(),
      creator_id: inserted_person.id,
      post_id: inserted_post.id,
      community_id: inserted_community.id,
      removed: false,
      deleted: false,
      path: Ltree(format!("0.{}", inserted_comment.id)),
      published_at: inserted_comment.published_at,
      updated_at: None,
      ap_id: Url::parse(&format!(
        "https://lemmy-alpha/comment/{}",
        inserted_comment.id
      ))?
      .into(),
      distinguished: false,
      local: true,
      language_id: LanguageId::default(),
      child_count: 1,
      controversy_rank: 0.0,
      downvotes: 0,
      upvotes: 1,
      score: 1,
      hot_rank: RANK_DEFAULT,
      report_count: 0,
      unresolved_report_count: 0,
      federation_pending: false,
      locked: false,
    };

    let child_comment_form = CommentInsertForm::new(
      inserted_person.id,
      inserted_post.id,
      inserted_community.id,
      "A child comment".into(),
    );
    let inserted_child_comment =
      Comment::create(pool, &child_comment_form, Some(&inserted_comment.path)).await?;

    // Comment Like
    let comment_like_form =
      CommentLikeForm::new(inserted_comment.id, inserted_person.id, Some(true));

    let inserted_comment_like = CommentActions::like(pool, &comment_like_form).await?;
    assert_eq!(Some(true), inserted_comment_like.vote_is_upvote);

    // Comment Saved
    let comment_saved_form = CommentSavedForm::new(inserted_person.id, inserted_comment.id);
    let inserted_comment_saved = CommentActions::save(pool, &comment_saved_form).await?;
    assert!(inserted_comment_saved.saved_at.is_some());

    let comment_update_form = CommentUpdateForm {
      content: Some("A test comment".into()),
      ..Default::default()
    };

    let updated_comment = Comment::update(pool, inserted_comment.id, &comment_update_form).await?;

    let read_comment = Comment::read(pool, inserted_comment.id).await?;
    let form = CommentLikeForm::new(inserted_comment.id, inserted_person.id, None);
    CommentActions::like(pool, &form).await?;
    let saved_removed = CommentActions::unsave(pool, &comment_saved_form).await?;
    let num_deleted = Comment::delete(pool, inserted_comment.id).await?;
    Comment::delete(pool, inserted_child_comment.id).await?;
    Post::delete(pool, inserted_post.id).await?;
    Community::delete(pool, inserted_community.id).await?;
    Person::delete(pool, inserted_person.id).await?;
    Instance::delete(pool, inserted_instance.id).await?;

    assert_eq!(expected_comment, read_comment);
    assert_eq!(expected_comment, updated_comment);
    assert_eq!(
      format!("0.{}.{}", expected_comment.id, inserted_child_comment.id),
      inserted_child_comment.path.0,
    );
    assert_eq!(UpleteCount::only_deleted(1), saved_removed);
    assert_eq!(1, num_deleted);

    Ok(())
  }

  #[tokio::test]
  #[serial]
  async fn test_aggregates() -> LemmyResult<()> {
    let pool = &build_db_pool_for_tests();
    let pool = &mut pool.into();

    let inserted_instance = Instance::read_or_create(pool, "my_domain.tld").await?;

    let new_person = PersonInsertForm::test_form(inserted_instance.id, "thommy_comment_agg");

    let inserted_person = Person::create(pool, &new_person).await?;

    let another_person = PersonInsertForm::test_form(inserted_instance.id, "jerry_comment_agg");

    let another_inserted_person = Person::create(pool, &another_person).await?;

    let new_community = CommunityInsertForm::new(
      inserted_instance.id,
      "TIL_comment_agg".into(),
      "nada".to_owned(),
      "pubkey".to_string(),
    );
    let inserted_community = Community::create(pool, &new_community).await?;

    let new_post = PostInsertForm::new(
      "A test post".into(),
      inserted_person.id,
      inserted_community.id,
    );
    let inserted_post = Post::create(pool, &new_post).await?;

    let comment_form = CommentInsertForm::new(
      inserted_person.id,
      inserted_post.id,
      inserted_community.id,
      "A test comment".into(),
    );
    let inserted_comment = Comment::create(pool, &comment_form, None).await?;

    let child_comment_form = CommentInsertForm::new(
      inserted_person.id,
      inserted_post.id,
      inserted_community.id,
      "A test comment".into(),
    );
    let _inserted_child_comment =
      Comment::create(pool, &child_comment_form, Some(&inserted_comment.path)).await?;

    let comment_like = CommentLikeForm::new(inserted_comment.id, inserted_person.id, Some(true));

    CommentActions::like(pool, &comment_like).await?;

    let comment_aggs_before_delete = Comment::read(pool, inserted_comment.id).await?;

    assert_eq!(1, comment_aggs_before_delete.score);
    assert_eq!(1, comment_aggs_before_delete.upvotes);
    assert_eq!(0, comment_aggs_before_delete.downvotes);

    // Add a post dislike from the other person
    let comment_dislike =
      CommentLikeForm::new(inserted_comment.id, another_inserted_person.id, Some(false));

    CommentActions::like(pool, &comment_dislike).await?;

    let comment_aggs_after_dislike = Comment::read(pool, inserted_comment.id).await?;

    assert_eq!(0, comment_aggs_after_dislike.score);
    assert_eq!(1, comment_aggs_after_dislike.upvotes);
    assert_eq!(1, comment_aggs_after_dislike.downvotes);

    // Remove the first comment like
    let form = CommentLikeForm::new(inserted_comment.id, inserted_person.id, None);
    CommentActions::like(pool, &form).await?;
    let after_like_remove = Comment::read(pool, inserted_comment.id).await?;
    assert_eq!(-1, after_like_remove.score);
    assert_eq!(0, after_like_remove.upvotes);
    assert_eq!(1, after_like_remove.downvotes);

    // Remove the parent post
    Post::delete(pool, inserted_post.id).await?;

    // Should be none found, since the post was deleted
    let after_delete = Comment::read(pool, inserted_comment.id).await;
    assert!(after_delete.is_err());

    // This should delete all the associated rows, and fire triggers
    Person::delete(pool, another_inserted_person.id).await?;
    let person_num_deleted = Person::delete(pool, inserted_person.id).await?;
    assert_eq!(1, person_num_deleted);

    // Delete the community
    let community_num_deleted = Community::delete(pool, inserted_community.id).await?;
    assert_eq!(1, community_num_deleted);

    Instance::delete(pool, inserted_instance.id).await?;

    Ok(())
  }

  #[tokio::test]
  #[serial]
  async fn test_update_children() -> LemmyResult<()> {
    let pool = &build_db_pool_for_tests();
    let pool = &mut pool.into();

    let inserted_instance = Instance::read_or_create(pool, "mydomain.tld").await?;
    let new_person = PersonInsertForm::test_form(inserted_instance.id, "john");
    let inserted_person = Person::create(pool, &new_person).await?;
    let new_community = CommunityInsertForm::new(
      inserted_instance.id,
      "test".into(),
      "test".to_owned(),
      "pubkey".to_string(),
    );
    let inserted_community = Community::create(pool, &new_community).await?;

    let new_post = PostInsertForm::new(
      "Post Title".to_string(),
      inserted_person.id,
      inserted_community.id,
    );
    let inserted_post = Post::create(pool, &new_post).await?;

    let parent_comment_form = CommentInsertForm::new(
      inserted_person.id,
      inserted_post.id,
      inserted_community.id,
      "Top level".to_string(),
    );
    let inserted_parent_comment = Comment::create(pool, &parent_comment_form, None).await?;

    let child_comment_form = CommentInsertForm::new(
      inserted_person.id,
      inserted_post.id,
      inserted_community.id,
      "Child".to_string(),
    );
    let inserted_child_comment = Comment::create(
      pool,
      &child_comment_form,
      Some(&inserted_parent_comment.path),
    )
    .await?;

    let grandchild_comment_form = CommentInsertForm::new(
      inserted_person.id,
      inserted_post.id,
      inserted_community.id,
      "Grandchild".to_string(),
    );
    let _inserted_grandchild_comment = Comment::create(
      pool,
      &grandchild_comment_form,
      Some(&inserted_child_comment.path),
    )
    .await?;

    let lock_form = CommentUpdateForm {
      locked: Some(true),
      ..Default::default()
    };

    let updated_comments =
      Comment::update_comment_and_children(pool, &inserted_parent_comment.path, &lock_form).await?;

    let locked_comments_num = updated_comments.iter().filter(|c| c.locked).count();

    assert_eq!(3, locked_comments_num);

    Ok(())
  }

  #[tokio::test]
  #[serial]
  async fn test_remove_post_children() -> LemmyResult<()> {
    let pool = &build_db_pool_for_tests();
    let pool = &mut pool.into();

    let inserted_instance = Instance::read_or_create(pool, "mydomain.tld").await?;
    let new_person = PersonInsertForm::test_form(inserted_instance.id, "sharah");
    let inserted_person = Person::create(pool, &new_person).await?;
    let new_community = CommunityInsertForm::new(
      inserted_instance.id,
      "test".into(),
      "test".to_owned(),
      "pubkey".to_string(),
    );
    let inserted_community = Community::create(pool, &new_community).await?;
    let new_post = PostInsertForm::new(
      "Post Title".to_string(),
      inserted_person.id,
      inserted_community.id,
    );
    let inserted_post = Post::create(pool, &new_post).await?;

    let comment_toplevel1_form = CommentInsertForm::new(
      inserted_person.id,
      inserted_post.id,
      inserted_community.id,
      "Top level".to_string(),
    );
    let inserted_comment_toplevel1 = Comment::create(pool, &comment_toplevel1_form, None).await?;

    let child_comment_form = CommentInsertForm::new(
      inserted_person.id,
      inserted_post.id,
      inserted_community.id,
      "Child".to_string(),
    );
    let _inserted_child_comment = Comment::create(
      pool,
      &child_comment_form,
      Some(&inserted_comment_toplevel1.path),
    )
    .await?;

    let comment_toplevel2_form = CommentInsertForm::new(
      inserted_person.id,
      inserted_post.id,
      inserted_community.id,
      "Top level 2".to_string(),
    );
    let _inserted_comment_toplevel2 = Comment::create(pool, &comment_toplevel2_form, None).await?;

    let updated_comments = Comment::update_removed_for_post(pool, inserted_post.id, true).await?;

    let updated_comments_num = updated_comments.iter().filter(|c| c.removed).count();

    assert_eq!(updated_comments_num, 3);

    Ok(())
  }
}