create or replace function public.sun_v17_log_error(p_workspace uuid, p_client_id text, p_app_version text, p_level text, p_message text, p_stack text, p_context jsonb default '{}'::jsonb) returns uuid language plpgsql security definer set search_path='public' as $$ declare v_id uuid; v_url text:=coalesce(p_context->>'url',''); v_message text:=left(coalesce(p_message,'Unknown error'),4000); v_level text:=left(coalesce(p_level,'error'),30); v_version text:=left(coalesce(p_app_version,''),80); begin if p_workspace is not null and public.sun_member_role(p_workspace) is null then raise exception 'Access denied'; end if; if v_url ~* '^file:' then return null; end if; select e.id into v_id from public.sun_v17_error_events e where e.workspace_id is not distinct from p_workspace and e.user_id is not distinct from auth.uid() and coalesce(e.app_version,'')=v_version and coalesce(e.level,'error')=v_level and e.message=v_message and e.created_at>=now()-interval '5 minutes' order by e.created_at desc limit 1; if v_id is not null then return v_id; end if; insert into public.sun_v17_error_events(workspace_id,user_id,client_id,app_version,level,message,stack,context) values(p_workspace,auth.uid(),left(p_client_id,120),v_version,v_level,v_message,left(coalesce(p_stack,''),12000),coalesce(p_context,'{}'::jsonb)) returning id into v_id; return v_id; end;$$; delete from public.sun_v17_error_events where coalesce(context->>'url','') ~* '^file:'; do $$ declare v_job bigint; begin select jobid into v_job from cron.job where jobname='caterium-error-retention'; if v_job is not null then perform cron.unschedule(v_job); end if; perform cron.schedule('caterium-error-retention','23 3 * * *',$cron$delete from public.sun_v17_error_events where created_at < now()-interval '30 days';$cron$); end$$;