From cf9cb8a8c6aef6f06643ca63474e434804d36794 Mon Sep 17 00:00:00 2001 From: Lephe Date: Sun, 1 Nov 2020 10:49:24 +0100 Subject: [PATCH] forum: add true, recursive deletion methods Each object has a .delete() which removes it and its owned subcontents. This delete() unfortunately has to commit the database session because circularly-dependent objects (such as a thread and its top comment) cannot be deleted together; two commits are needed. --- app/models/comment.py | 5 +++++ app/models/forum.py | 7 +++++++ app/models/thread.py | 13 +++++++++++++ app/models/topic.py | 5 +++++ 4 files changed, 30 insertions(+) diff --git a/app/models/comment.py b/app/models/comment.py index a27617c..8c7be13 100644 --- a/app/models/comment.py +++ b/app/models/comment.py @@ -39,5 +39,10 @@ class Comment(Post): self.text = new_text self.touch() + def delete(self): + """Recursively delete post and all associated contents.""" + # FIXME: Attached files? + db.session.delete(self) + def __repr__(self): return f'' diff --git a/app/models/forum.py b/app/models/forum.py index 0e07687..f1cfe60 100644 --- a/app/models/forum.py +++ b/app/models/forum.py @@ -41,5 +41,12 @@ class Forum(db.Model): # TODO: optimize this with real ORM return sum(t.thread.comments.count() for t in self.topics) + def delete(self): + """Recursively delete forum and all associated contents.""" + for t in self.topics: + t.delete() + db.session.commit() + db.session.delete(self) + def __repr__(self): return f'' diff --git a/app/models/thread.py b/app/models/thread.py index e623fee..418c6bc 100644 --- a/app/models/thread.py +++ b/app/models/thread.py @@ -52,5 +52,18 @@ class Thread(db.Model): return self.owner_program[0] return None + def delete(self): + """Recursively delete thread and all associated contents.""" + # Remove reference to top comment + self.top_comment = None + db.session.add(self) + db.session.commit() + # Remove comments + for c in self.comments: + c.delete() + # Remove thread + db.session.commit() + db.session.delete(self) + def __repr__(self): return f'' diff --git a/app/models/topic.py b/app/models/topic.py index 1dcd8a8..307b1fc 100644 --- a/app/models/topic.py +++ b/app/models/topic.py @@ -51,5 +51,10 @@ class Topic(Post): self.thread = thread self.forum = forum + def delete(self): + """Recursively delete topic and all associated contents.""" + self.thread.delete() + db.session.delete(self) + def __repr__(self): return f''