I have two transactions. One that assign tags to post after it's creation (Transaction B). Another transaction (Transaction A) deletes tags which are no longer used by any post. It's being done after post deletion.
Transaction A
SELECT COUNT(*) FROM post_tags WHERE tag_id = 45;
Transaction B
SELECT id FROM tag WHERE name = 'rss';
Transaction A
DELETE FROM tag WHERE id = 45;
Transaction B
-- Now, foreign key violation
INSERT INTO post_tags(post_id, tag_id) VALUES(123, 45);
I know I can use SELECT FOR UPDATE in both transaction, but I don't want to lock transactions which just assign tags. I want them to lock only if there is a transaction which is trying to delete the tag.