I'm fairly new to Postgres but I've created a function via pgAdmin 4.15, Postgres is at version 9.6.
Problem is I can't make it work, I think there is something wrong in the syntax?
INSERT and UPDATE statements are working (outside the function), so it must be the function syntax...
The intention is to call this function via a jdbc plugin (Logstash) and update some tables using the given "input" string as key.
The "key" is used to SELECT the alarm IDs to operate on.
So, for every id I get, I need to perform some UPDATE/INSERT on those tables.
# \sf close_event
CREATE OR REPLACE FUNCTION public.close(input text)
RETURNS void
LANGUAGE plpgsql
AS $function$
DECLARE
_event_idnumber INTEGER;
BEGIN
FOR _event_idnumber IN
SELECT id FROM public.alerts WHERE data ->> 'field_name' = input
LOOP
INSERT INTO public.comments ( created_date, content, alert_id, user_id) VALUES (current_timestamp, 'text1 text', _event_idnumber, 1);
INSERT INTO public.comments ( created_date, content, alert_id, user_id) VALUES (current_timestamp, 'text2 text.', _event_idnumber, 1);
INSERT INTO public.analysis ( alert_id, created_date, last_updated, notes) VALUES (_event_idnumber, current_timestamp, current_timestamp, 'text3 text');
UPDATE public.alerts SET status='DONE', outcome='completed', last_updated=current_timestamp, assigned_user_id=1 WHERE id = _event_idnumber;
UPDATE public.alerts SET data = jsonb_set(data, '{other_field}'::text[], input::jsonb) WHERE id = _event_idnumber;
END LOOP;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
END;
$function$;
I've read that with some versions of postgres I must use a DO statement, but can't figure out how.
I'm following instructions at this page: https://www.postgresql.org/docs/9.6/plpgsql-control-structures.html