CREATE FUNCTION pg_task_notify_on_error()
RETURNS trigger AS $$
BEGIN
  PERFORM pg_notify('pg_task_error', NEW.id::text);
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

COMMENT ON FUNCTION pg_task_notify_on_error
IS 'Notifies listeners when a task enters the terminal error state';

CREATE TRIGGER pg_task_error_insert
AFTER INSERT
ON pg_task
FOR EACH ROW
WHEN (NEW.error IS NOT NULL)
EXECUTE PROCEDURE pg_task_notify_on_error();

CREATE TRIGGER pg_task_error_update
AFTER UPDATE OF error
ON pg_task
FOR EACH ROW
WHEN (OLD.error IS NULL AND NEW.error IS NOT NULL)
EXECUTE PROCEDURE pg_task_notify_on_error();
