File: /volume1/@appstore/SynologyPhotos/etc/sql/27.sql
DELETE FROM many_unit_has_many_person WHERE (id_unit, id_person, id_user) NOT IN (select id_unit, id_filter, id_user from filter where filter_type = 'person');
CREATE OR REPLACE FUNCTION public.update_many_unit_has_many_person_func()
RETURNS trigger
LANGUAGE plpgsql
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 1
AS $$
DECLARE
many_unit_has_many_person_table text;
BEGIN
IF (NEW.filter_type = 'person' OR OLD.filter_type = 'person') THEN
many_unit_has_many_person_table = TG_TABLE_SCHEMA || '.many_unit_has_many_person';
IF (TG_OP = 'INSERT') THEN
EXECUTE format('INSERT INTO %s (id_unit, id_person, id_user) VALUES (%L, %L, %L) ON CONFLICT (id_unit, id_person) DO NOTHING', many_unit_has_many_person_table, NEW.id_unit, NEW.id_filter, NEW.id_user);
ELSIF (TG_OP = 'DELETE') THEN
EXECUTE format('DELETE FROM %s WHERE id_unit = %L and id_person = %L', many_unit_has_many_person_table, OLD.id_unit, OLD.id_filter);
ELSIF (TG_OP = 'UPDATE') THEN
EXECUTE format('UPDATE %s SET id_person = %L WHERE id_unit = %L AND id_user = %L AND id_person = %L', many_unit_has_many_person_table, NEW.id_filter, NEW.id_unit, NEW.id_user, OLD.id_filter);
END IF;
END IF;
RETURN NULL;
END;
$$;