Last active
July 13, 2016 19:18
-
-
Save splbio/f310d26f810b0dfeaf4ec0ada5826763 to your computer and use it in GitHub Desktop.
Prevent creation of too many associated rows in postgresql trigger.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TRIGGER "Q_limit_answers_per_question" AFTER INSERT or UPDATE on question_answer | |
FOR EACH ROW EXECUTE PROCEDURE question_answer_insert(); | |
CREATE OR REPLACE FUNCTION question_answer_insert() | |
RETURNS TRIGGER AS | |
$body$ | |
BEGIN | |
-- Lock the existing rows to prevent race condition with other txns. | |
PERFORM * FROM question_answer WHERE question_id = NEW.question_id for UPDATE; | |
-- Only allow insert/update if doesn't violate the constraints. | |
IF (SELECT count(id) FROM question_answer where question_id = NEW.question_id) > 4 | |
THEN | |
RAISE EXCEPTION 'Too many rows for question %', NEW.question_id; | |
END IF; | |
RETURN NEW; | |
END; | |
$body$ | |
LANGUAGE plpgsql; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment