I'm trying to make a list of users who are modified and then at the end of transaction I would like to process the list. Here's how I'm trying to do this:
CREATE TABLE "user"(
user_id bigserial NOT NULL,
username varchar(255) NOT NULL,
CONSTRAINT pk_5 PRIMARY KEY (user_id)
);
CREATE FUNCTION enlist_user ()
RETURNS trigger
LANGUAGE plpgsql
AS $$
DECLARE
rec record;
BEGIN
IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
rec := NEW;
ELSE
rec := OLD;
END IF;
CREATE TEMPORARY TABLE IF NOT EXISTS user_list (
user_id bigint NOT NULL,
CONSTRAINT user_queue_pk PRIMARY KEY (user_id)
);
INSERT INTO user_list
VALUES (rec.user_id);
EXCEPTION WHEN OTHERS THEN
RAISE NOTICE 'Unable to add %', rec.user_id;
RETURN rec;
END;
$$;
CREATE TRIGGER user_modified
AFTER INSERT OR DELETE OR UPDATE
ON "user"
FOR EACH ROW
EXECUTE PROCEDURE enlist_user();
INSERT INTO "user" VALUES (default, 'qwe');
But running the above code results in follow error:
ERROR: control reached end of trigger procedure without RETURN
CONTEXT: PL/pgSQL function enlist_user()
What's going on? Why RETURN rec did not work?
return recis inside theexceptionblock (which is hidden by your "wrong" indention). If no exception is thrown that line is never reached.endthat you already have. But if no exception is raised, it won't be executed. Logically the keywordexceptionis on the same level as yourbegin- the indention you have is misleading.