ALTER TABLE signs_detect.sign_feature DROP CONSTRAINT IF EXISTS sign_feature_feature_id_fkey CASCADE;

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)
            OR
            EXISTS(SELECT * FROM signals.ride_photo 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 CONSTRAINT TRIGGER constraint_feature_id_exists
    AFTER INSERT OR UPDATE ON signs_detect.sign_feature
    FOR EACH ROW EXECUTE PROCEDURE check_feature_id_exists();
