From 063fd09224a6263cda61fafe0a5d9aade4cf04fc Mon Sep 17 00:00:00 2001 From: Michael Tremer Date: Thu, 22 Feb 2024 19:00:45 +0000 Subject: [PATCH] nopaste: Tidy up the cleanup task Signed-off-by: Michael Tremer --- src/backend/base.py | 4 ++++ src/backend/nopaste.py | 35 ++++++++++++++++++++++++++--------- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/src/backend/base.py b/src/backend/base.py index 4af92e27..9f013f90 100644 --- a/src/backend/base.py +++ b/src/backend/base.py @@ -234,3 +234,7 @@ class Backend(object): # Cleanup in accounts with self.db.transaction(): self.accounts.cleanup() + + # Cleanup nopasts + with self.db.transaction(): + self.nopaste.cleanup() diff --git a/src/backend/nopaste.py b/src/backend/nopaste.py index 1d7ecad0..7cda2b8a 100644 --- a/src/backend/nopaste.py +++ b/src/backend/nopaste.py @@ -22,8 +22,6 @@ class Nopaste(Object): return self.db.fetch_one(Paste, query, *args, **kwargs) def create(self, content, subject=None, mimetype=None, expires=None, account=None, address=None): - self._cleanup_database() - # Store the blob blob_id = self._store_blob(content) @@ -140,13 +138,32 @@ class Nopaste(Object): self.db.execute("UPDATE nopaste SET time_lastseen = NOW(), views = views + 1 \ WHERE uuid = %s", uuid) - def _cleanup_database(self): - # Delete old pastes when they are expired or when they have not been - # accessed in a long time. - self.db.execute("DELETE FROM nopaste WHERE (CASE \ - WHEN time_expires IS NULL \ - THEN time_lastseen + INTERVAL '6 months' <= NOW() \ - ELSE NOW() >= time_expires END)") + def cleanup(self): + """ + Removes all expired pastes and removes any unneeded blobs + """ + # Remove all expired pastes + self.db.execute(""" + DELETE FROM + nopaste + WHERE + expires_at < CURRENT_TIMESTAMP + """) + + # Remove unneeded blobs + self.db.execute(""" + DELETE FROM + nopaste_blobs + WHERE NOT EXISTS + ( + SELECT + 1 + FROM + nopaste + WHERE + nopaste.blob_id = nopaste_blobs.id + ) + """) class Paste(Object): -- 2.39.2