Skip to content

Commit 7ff15fa

Browse files
author
LL201314-II
committed
fix: cascade purge attachments, comments, and votes when post/comment is deleted
When a post is set to PostDeleted via setPostResponse: - Soft-delete all associated comments (set deleted_at) - Delete all attachments (both post-level and comment-level) - Delete all post_votes When a comment is soft-deleted via deleteComment: - Delete comment-level attachments This prevents orphaned data from accumulating in the DB over time. Fixes #1149
1 parent b8c970d commit 7ff15fa

2 files changed

Lines changed: 39 additions & 0 deletions

File tree

app/services/sqlstore/postgres/comment.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,15 @@ func deleteComment(ctx context.Context, c *cmd.DeleteComment) error {
8787
); err != nil {
8888
return errors.Wrap(err, "failed delete comment")
8989
}
90+
91+
// Delete attachments associated with this comment
92+
if _, err := trx.Execute(
93+
"DELETE FROM attachments WHERE comment_id = $1 AND tenant_id = $2",
94+
c.CommentID, tenant.ID,
95+
); err != nil {
96+
return errors.Wrap(err, "failed to delete comment attachments")
97+
}
98+
9099
return nil
91100
})
92101
}

app/services/sqlstore/postgres/post.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,36 @@ func setPostResponse(ctx context.Context, c *cmd.SetPostResponse) error {
157157
return errors.Wrap(err, "failed to update post's response")
158158
}
159159

160+
// When a post is deleted, purge associated data
161+
if c.Status == enum.PostDeleted {
162+
// Soft-delete all comments on this post
163+
_, err = trx.Execute(`
164+
UPDATE comments SET deleted_at = $1, deleted_by_id = $2
165+
WHERE post_id = $3 AND tenant_id = $4 AND deleted_at IS NULL
166+
`, respondedAt, user.ID, c.Post.ID, tenant.ID)
167+
if err != nil {
168+
return errors.Wrap(err, "failed to soft-delete comments for deleted post")
169+
}
170+
171+
// Delete all attachments related to this post (both post-level and comment-level)
172+
_, err = trx.Execute(`
173+
DELETE FROM attachments
174+
WHERE post_id = $1 AND tenant_id = $2
175+
`, c.Post.ID, tenant.ID)
176+
if err != nil {
177+
return errors.Wrap(err, "failed to delete attachments for deleted post")
178+
}
179+
180+
// Delete all votes for this post
181+
_, err = trx.Execute(`
182+
DELETE FROM post_votes
183+
WHERE post_id = $1 AND tenant_id = $2
184+
`, c.Post.ID, tenant.ID)
185+
if err != nil {
186+
return errors.Wrap(err, "failed to delete votes for deleted post")
187+
}
188+
}
189+
160190
c.Post.Status = c.Status
161191
c.Post.Response = &entity.PostResponse{
162192
Text: c.Text,

0 commit comments

Comments
 (0)