Basically I have a few different tables which share an array field job_ids and each has their own status which is also an integer. On the job table, id is its primary key.
Postgres version 12.5
Table table1:
CREATE TABLE table1 (
id serial NOT NULL,
jobs_ids _int4 NULL,
status int4 NULL,
CONSTRAINT cable_pkey PRIMARY KEY (id)
Table job:
CREATE TABLE job (
id serial NOT NULL,
description varchar NULL,
created_at timestamptz NULL DEFAULT now(),
modified_at timestamptz NULL DEFAULT now(),
CONSTRAINT job_pkey PRIMARY KEY (id)
My trigger function:
CREATE OR REPLACE FUNCTION new_job_id_table1()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
BEGIN
if new.status= 3 and new.jobs_ids = '{}' then
insert into job (description, type_id)
select 'automated jobid with id=' || new.id, 1;
new.jobs_ids := array[ max(b.id) ] from job b
where new.jobs_ids = '{}' and b.type_id = 1;
end if;
RETURN NEW;
END;
$function$;
Trigger, set to run before update:
create trigger job_id_trigger_table1
before update of status on table1
for each row execute function new_job_id_table1();
Users update stuff through qgis but usually it's:
update table1 set status = 3 where id = $whatever_id_they_picked;
It creates a new entry in the job table and assigns that id to the updated row in table1.
It works fine if the user updates one row in table1 to status 3. However, it does nothing when a user updates multiple rows at a time.
If multiple rows are updated at once, I would like to generate only one job id for to several rows in table1 instead of (currently) multiple.
How to make the trigger work with multi-row updates?