Skip to content

Instantly share code, notes, and snippets.

@splbio
Last active July 13, 2016 19:18
Show Gist options
  • Save splbio/f310d26f810b0dfeaf4ec0ada5826763 to your computer and use it in GitHub Desktop.
Save splbio/f310d26f810b0dfeaf4ec0ada5826763 to your computer and use it in GitHub Desktop.
Prevent creation of too many associated rows in postgresql trigger.
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