From 55e7ee145c470e832b56c9540f520aedf8792c15 Mon Sep 17 00:00:00 2001 From: Parker Date: Thu, 19 Dec 2024 16:35:18 -0600 Subject: Add database cleanup scheduler --- api/util/clean_db.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 api/util/clean_db.py (limited to 'api/util') diff --git a/api/util/clean_db.py b/api/util/clean_db.py new file mode 100644 index 0000000..11438aa --- /dev/null +++ b/api/util/clean_db.py @@ -0,0 +1,25 @@ +import datetime + +from api.util.db_dependency import get_db +from models import Link, Log + +""" +Remove expired short links and their associated logs +""" + + +def clean_db(): + db = next(get_db()) + # Get all expired short links + expired_links = ( + db.query(Link) + .filter(Link.expire_date < datetime.datetime.today()) + .all() + ) + + # Delete all expired short links and their logs + for link in expired_links: + logs = db.query(Log).filter(Log.link == link.link).all() + for log in logs: + db.delete(log) + db.delete(link) -- cgit v1.2.3-70-g09d2