do $$ declare definition text; original text; lookup text := 'and start_time = v_start and end_time = v_end'; marker text := '-- Find or create the slot by (event, date, start, end).'; begin select pg_get_functiondef('public.sync_sessionize_event(uuid,jsonb)'::regprocedure) into original; if length(original) - length(replace(original, lookup, '')) <> length(lookup) or position(marker in original) = 0 then raise exception 'Unexpected Sessionize sync definition; refusing unsafe replacement'; end if; definition := replace(original, lookup, lookup || E'\n and type = case when v_service then ''service_session''::public.slot_type else ''session''::public.slot_type end'); definition := replace(definition, marker, $replacement$ if v_service and not exists (select 1 from public.sessions where external_id = v_ext) then update public.sessions se set external_id = v_ext from public.slots sl where se.slot_id = sl.id and se.event_id = p_event_id and se.external_id like 'manual-service-%' and se.title = v_title and sl.type = 'service_session' and sl.slot_date = v_date and sl.start_time = v_start and sl.end_time = v_end and (select count(*) from public.sessions candidate join public.slots candidate_slot on candidate_slot.id = candidate.slot_id where candidate.event_id = p_event_id and candidate.external_id like 'manual-service-%' and candidate.title = v_title and candidate_slot.type = 'service_session' and candidate_slot.slot_date = v_date and candidate_slot.start_time = v_start and candidate_slot.end_time = v_end) = 1; end if; $replacement$ || marker); execute definition; end; $$;