--
-- cal_uid__upsert/3
--
create or replace function cal_uid__upsert(
  p_cal_uid text,
  p_activity_id integer,
  p_ical_vars text
) returns void as $$

BEGIN
    LOOP
    --
    -- We might have duplicates on the activity_id and on the cal_uid,
    -- both should be unique.
    --
    update cal_uids
        set   ical_vars = p_ical_vars
	where cal_uid = p_cal_uid;
        IF found THEN
            return;
        END IF;
        -- not there, so try to insert the key
        -- if someone else inserts the same key concurrently,
        -- we could get a unique-key failure
        BEGIN
	    -- Try to delete entry to avoid duplicates (might fail)
	    delete from cal_uids where on_which_activity = p_activity_id;
	    -- Insert value
	    insert into cal_uids 
                (cal_uid, on_which_activity, ical_vars)
            values
                (p_cal_uid, p_activity_id,  p_ical_vars);
            RETURN;
            EXCEPTION WHEN unique_violation THEN
            -- Do nothing, and loop to try the UPDATE again.
        END;
    END LOOP;
END;
$$ language plpgsql;