ALTER TABLE queue_tickets
    ADD COLUMN reissued_from_ticket_id uuid;

ALTER TABLE queue_tickets
    ADD CONSTRAINT queue_tickets_reissued_from_project_fk
        FOREIGN KEY (reissued_from_ticket_id, project_id)
        REFERENCES queue_tickets(id, project_id)
        ON DELETE RESTRICT,
    ADD CONSTRAINT queue_tickets_reissued_from_not_self_check
        CHECK (reissued_from_ticket_id IS NULL OR reissued_from_ticket_id <> id),
    ADD CONSTRAINT queue_tickets_reissued_from_once_unique
        UNIQUE (reissued_from_ticket_id);

CREATE INDEX queue_tickets_reissued_from_idx
    ON queue_tickets (project_id, reissued_from_ticket_id)
    WHERE reissued_from_ticket_id IS NOT NULL;
