Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trigger not executing as expected

I’m trying to implement this trigger that ensures an user can’t comment on their own publications.

CREATE OR REPLACE FUNCTION not_comment() RETURNS TRIGGER AS 
$BODY$ 

BEGIN 
       IF EXISTS (SELECT *
        FROM 
        (SELECT publisherID FROM comment INNER JOIN post USING (postID) WHERE NEW.postID = post.postID) AS comment_userID,
        (SELECT publisherID FROM article INNER JOIN post USING (postID) WHERE NEW.articleID = article.articleID) AS article_userID
        WHERE comment_userID.publisherID = article_userID.publisherID) THEN
       RAISE EXCEPTION 'A user cannot comment an article that publish'; 
       END IF; 
       RETURN NEW; 
END 
$BODY$ 
LANGUAGE plpgsql; 
 
CREATE TRIGGER not_comment 
      BEFORE INSERT ON comment
      FOR EACH ROW 
      EXECUTE PROCEDURE not_comment(); 

The inner query is working as expected for the test cases, but for some reason the condition isn’t being activated.

The same syntax as other working triggers was used.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any idea of what’s going on?

>Solution :

The trigger is fired before the row is inserted, so you should assume in the condition that the row is already in the table. Thus the first subquery should look like

    (SELECT publisherid FROM post WHERE new.postid = post.postid) AS comment_userID
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading