Skip to content
Advertisement

Is it possible to pass a built in function as an argument to a trigger?

I ask this question in light of the following trigger producing this error:

ERROR: syntax error at or near "("
LINE 5: ...cessBlogPostApproval"('Blog Post Approval', concat('Your blo...
^

The trigger in question:

CREATE TRIGGER "processBlogPostApproval_AFTER_INSERT"
    AFTER INSERT
    ON public."ApprovedBlogPosts"
    FOR EACH ROW
    EXECUTE PROCEDURE public."processBlogPostApproval"('Blog Post Approval', concat('Your blog post, "', SELECT "Title" FROM public."BlogPosts" WHERE "PostID" == NEW."PostID", '"has been approved.'));

The problem seems to be arising due to the fact that I passed a concatenation function as my second argument, or rather, that I did not pass it correctly. Would appreciate your assistance in identifying which of the two is the cause of the problem.

Advertisement

Answer

Sometimes it turns out the easiest/cleanest way to do something is — well not to do it. This seems to be the case here. The issue you are having deal with passing a message into a trigger function, that getting it properly formatted. Well since a trigger function must defined without parameters.

A trigger procedure is created with the CREATE FUNCTION command, declaring it as a function with no arguments and a return type of trigger.

Don’t do it. Build the message in the trigger function. It actually makes the code there easier (IMO). You didn’t provide much detail so just a minimal example:

-- setup
create table approved_blog_posts( id integer ) ;
create table blog_posts(id integer, title text) ;

insert into blog_posts( id, title) 
values (1 ,'Blog Rant') 
     , (2 ,'Still Rant again')
     , (3 ,'Rambling about nut''en!');

-- trigger function 
create or replace function blog_post_approved()
  returns  trigger
  language plpgsql
as $$
declare
    l_title text; 
begin 
     select title
       into l_title
       from blog_posts
      where id = new.id;

    raise notice 'Your blog post "%" has been approved.',l_title;
    return new;
end; 
$$;  

-- attach trigger to table    
create trigger approved_blog_posts_air
    after insert
    on approved_blog_posts
    for each row
    execute procedure blog_post_approved();

 -- demo/test
 insert into approved_blog_posts(id) values (1),(3);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement