commit the delete query for each user in the loop to reduce lock time

This commit is contained in:
Hongbo Wu 2024-06-12 19:09:40 +08:00
parent f29592d671
commit fb5ef3422c
2 changed files with 23 additions and 3 deletions

View file

@ -4,7 +4,9 @@
BEGIN;
CREATE OR REPLACE FUNCTION batch_delete_trash_items()
CREATE OR REPLACE PROCEDURE batch_delete_trash_items(
minimum_items INT
)
RETURNS VOID AS $$
DECLARE
user_record RECORD;
@ -17,14 +19,32 @@ DECLARE
status = 'ACTIVE';
BEGIN
FOR user_record IN user_cursor LOOP
BEGIN;
-- For Row Level Security
PERFORM omnivore.set_claims(user_record.id, 'omnivore_user');
-- keep the minimum number of items in trash
DELETE FROM omnivore.library_item
WHERE
user_id = user_record.id
AND state = 'DELETED'
AND deleted_at < NOW() - INTERVAL '14 days';
AND deleted_at < NOW() - INTERVAL '14 days'
AND id NOT IN (
SELECT
id
FROM
omnivore.library_item
WHERE
user_id = user_record.id
AND state = 'DELETED'
AND deleted_at < NOW() - INTERVAL '14 days'
ORDER BY
deleted_at DESC
LIMIT minimum_items
);
COMMIT;
END LOOP;
END;
$$ LANGUAGE plpgsql;

View file

@ -4,6 +4,6 @@
BEGIN;
DROP FUNCTION IF EXISTS batch_delete_trash_items();
DROP PROCEDURE IF EXISTS batch_delete_trash_items();
COMMIT;