fp/services/migrations-schema/migrations/00004_create-trigger-functi...

30 lines
1.1 KiB
PL/PgSQL

-- We create a function which lets Postgrest's automation user create jobs in Graphile Worker.
-- Normally only the database owner, in our case `postgres`, can add jobs due to RLS in graphile_worker tables.
-- Under the advice of graphile_worker author, we can use a SECURITY DEFINER wrapper function.
-- @see https://worker.graphile.org/docs/sql-add-job#graphile_workeradd_job:~:text=graphile_worker.add_job(...),that%20are%20necessary.)
-- @see https://discord.com/channels/489127045289476126/1179293106336694333/1179605043729670306
-- @see https://discord.com/channels/489127045289476126/498852330754801666/1067707497235873822
CREATE FUNCTION public.tg__add_job() RETURNS trigger
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO 'pg_catalog', 'public', 'pg_temp'
AS $$
begin
PERFORM graphile_worker.add_job(tg_argv[0], json_build_object(
'url', NEW.url,
'record_id', NEW.id
), max_attempts := 12);
return NEW;
end;
$$;
CREATE TRIGGER record
AFTER INSERT ON api.records
FOR EACH ROW
EXECUTE PROCEDURE public.tg__add_job('record');