Postgresql – How to send a parameter to a trigger function from an external resource

plpgsqlpostgresqltrigger

I have a trigger that executes before delete to audit changes in tables. The problem I have is that one of the fields I save in the xtable_audit table is the user id (of an user table) that is used in the web application. How can I send that external iduser from the web application to the trigger function when a delete occurs in any table that has that trigger?

Best Answer

You could use the set_config() and current_setting() functions for that. In the application just after establishing the database connection you call something like

select set_config('myapp.app_user','johnny',false);

to set a custom configuration variable for the session. In the trigger you then use

select into v_actualuser current_setting('myapp.app_user');

to retrieve the value.

This blog post even has a sample trigger for your viewing pleasure.