0

I created this trigger for a flight booking database where the trigger is meant to prevent reserved bookings from being deleted when using a delete sql statement. I have two statuses. One is 'r' for reserved and the other is 'c' for cancelled. My mission is to ensure that reserved bookings cannot be deleted and if a user tries to delete one, it raises the exception that's shown in my example trigger.

I have created this trigger and it has executed successfully but when I test it by deleting a reserved booking with status 'r' it runs and says "query returned successfully: one row affected..." which is not what I want. I want it to raise the exception and not delete the booking.

CREATE FUNCTION prevent_deletion() RETURNS trigger AS $prevent_deletion$

        BEGIN            
            IF 'status' = 'r' THEN
                RAISE EXCEPTION 'You cannot delete reserved bookings';
            END IF;
            RETURN NEW;

        END;
    $prevent_deletion$ LANGUAGE plpgsql;

    CREATE TRIGGER prevent_deletion AFTER DELETE ON flightbooking
        FOR EACH ROW EXECUTE PROCEDURE prevent_deletion();
2
  • You need a BEFORE DELETE trigger. Commented Apr 10, 2017 at 14:51
  • @J.Doe: In a BEFORE trigger, the triggering operation is aborted if you return NULL, and NEW is NULL in your case (there's no "new" record for a DELETE). Try RETURN OLD instead. Commented Apr 10, 2017 at 15:26

1 Answer 1

2

This line:

IF 'status' = 'r' THEN

...compares the string 'status' to the string 'r' (and of course, they're never going to be equal...).

Comparing the field status to the string 'r' would look like this:

IF OLD.status = 'r' THEN
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.