CREATE TABLE service.diffalert_task (
    id bigint PRIMARY KEY REFERENCES service.task (id),
    old_branch_id bigint NOT NULL,
    old_commit_id bigint NOT NULL,
    new_branch_id bigint NOT NULL,
    new_commit_id bigint NOT NULL
);


CREATE SCHEMA diffalert;


SET search_path = diffalert, public;

CREATE TABLE message_attributes (
    attributes_id serial PRIMARY KEY,
    description text NOT NULL
);


CREATE OR REPLACE FUNCTION insert_message_attributes(
    p_description text)
RETURNS integer AS
$$
DECLARE
    r_attributes_id integer;
BEGIN
    LOOP
        SELECT attributes_id INTO r_attributes_id
            FROM diffalert.message_attributes
            WHERE description = p_description;
        IF FOUND THEN
            RETURN r_attributes_id;
        END IF;

        BEGIN
            INSERT INTO diffalert.message_attributes
                    (description)
                VALUES (p_description)
                RETURNING attributes_id INTO r_attributes_id;
            RETURN r_attributes_id;
        EXCEPTION WHEN unique_violation THEN
            -- try SELECT again
        END;
    END LOOP;
END;
$$ LANGUAGE plpgsql;


CREATE TABLE messages (
    id bigserial PRIMARY KEY,
    task_id bigint NOT NULL,
    object_id bigint NOT NULL,
    pri_major integer NOT NULL,
    pri_minor integer NOT NULL,
    attributes_id integer NOT NULL
);


CREATE INDEX messages_order_index
    ON messages (task_id, pri_major, pri_minor);

SET search_path = public;
