Skip to content

Commit

Permalink
Only delete versions of closed documents older than 30 days
Browse files Browse the repository at this point in the history
  • Loading branch information
egli committed Jan 9, 2025
1 parent 7448deb commit 7c7d939
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions resources/sql/queries.sql
Original file line number Diff line number Diff line change
Expand Up @@ -170,26 +170,28 @@ VALUES (:comment, :document-id, :content, :user)
DELETE FROM documents_version WHERE id = :id

-- :name get-old-versions-of-closed-documents :? :*
-- :doc Get old versions that belong to any document that is in "closed" state
-- :doc Get versions older than 30 days that belong to a document that is in "closed" state
SELECT * FROM documents_version version
JOIN documents_document doc
ON version.document_id = doc.id
JOIN documents_state state
ON doc.state_id = state.id
WHERE state.name = "closed"
AND version.created_at < NOW() - INTERVAL 30 DAY -- older than 30 days
AND version.id NOT IN (
SELECT MAX(id) FROM documents_version
GROUP BY document_id)

-- :name delete-old-versions-of-closed-documents :! :n
-- :doc Remove old versions that belong to any document that is in "closed" state
-- :doc Remove versions older than 30 days that belong to a document that is in "closed" state
DELETE version
FROM documents_version version
JOIN documents_document doc
ON version.document_id = doc.id
JOIN documents_state state
ON doc.state_id = state.id
WHERE state.name = "closed"
AND version.created_at < NOW() - INTERVAL 30 DAY -- older than 30 days
AND version.id NOT IN (
-- the nested select is needed to avoid a mysql error, see https://stackoverflow.com/a/43171707
SELECT * FROM (
Expand Down

0 comments on commit 7c7d939

Please sign in to comment.