CREATE OR REPLACE FUNCTION check_feature_id_exists() RETURNS TRIGGER AS $$
DECLARE
    flag boolean;
BEGIN
    flag := (
        SELECT EXISTS(SELECT * FROM signals.feature WHERE feature_id = NEW.feature_id)
    );

    IF NOT flag THEN
        RAISE EXCEPTION 'Unknown feature id %!', NEW.feature_id;
    END IF;

    RETURN NEW;
END;
$$ language plpgsql;

CREATE OR REPLACE FUNCTION delete_sign_feature_on_feature_deletion() RETURNS TRIGGER AS $$
DECLARE
BEGIN
    DELETE FROM signs_detect.sign_feature WHERE feature_id = OLD.feature_id;
    RETURN OLD;
END;
$$ language plpgsql;

CREATE TRIGGER delete_sign_feature_on_feature_deletion
    AFTER DELETE ON  signals.feature
    FOR EACH ROW EXECUTE PROCEDURE delete_sign_feature_on_feature_deletion();

CREATE TRIGGER delete_sign_feature_on_feature_deletion
    AFTER DELETE ON signals.ride_photo
    FOR EACH ROW EXECUTE PROCEDURE delete_sign_feature_on_feature_deletion();

CREATE TRIGGER delete_sign_feature_on_feature_deletion
    AFTER DELETE ON signals.assignment_photo
    FOR EACH ROW EXECUTE PROCEDURE delete_sign_feature_on_feature_deletion();
