CREATE TABLE eye.recognition_task (
    recognition_task_id bigserial PRIMARY KEY,
    parent_id bigint REFERENCES eye.recognition_task (recognition_task_id) ON DELETE CASCADE,
    recognition_id bigint NOT NULL REFERENCES eye.recognition (recognition_id) ON DELETE CASCADE,
    task_id bigint NOT NULL REFERENCES toloka_mgr.task (id) ON DELETE CASCADE,
    txn_id bigint NOT NULL,

    UNIQUE(task_id)
);

CREATE OR REPLACE FUNCTION check_recognition_id_equal() RETURNS TRIGGER AS $$
DECLARE
    flag boolean;
BEGIN
    IF NEW.parent_id is NULL THEN
        RETURN NEW;
    END IF;

    flag := (
        SELECT EXISTS(
            SELECT * FROM eye.recognition_task
            WHERE recognition_task_id = NEW.parent_id AND recognition_id = NEW.recognition_id
        )
    );

    IF NOT flag THEN
        RAISE EXCEPTION 'There is no recognition task with same recognition id and id %!', NEW.parent_id;
    END IF;

    RETURN NEW;
END;
$$ language plpgsql;

CREATE TRIGGER constraint_equal_recognition_id_in_parent_recognition_task
    AFTER INSERT OR UPDATE ON eye.recognition_task
    FOR EACH ROW EXECUTE PROCEDURE check_recognition_id_equal();

CREATE INDEX eye_toloka_parent_id_index ON eye.recognition_task USING btree(parent_id);
CREATE INDEX eye_toloka_recognition_id_index ON eye.recognition_task USING btree(recognition_id);
CREATE INDEX eye_toloka_txn_id_index ON eye.recognition_task USING btree(txn_id);
