14

I would like to execute external program (such as .net c# console) when PostgreSQL trigger is fired. How can I achieve it?

2
  • Why my question was voted down? any reason? Feb 7, 2014 at 18:22
  • Of course, I have been searching solution. I still cannot find better and faster solution. Any alternative solution is ok. Feb 7, 2014 at 19:00

3 Answers 3

15

Postgres cannot normally run external programs for security reasons.

The typical solution is to use NOTIFY and have a daemon LISTEN to it. There are solutions for every major scripting language out there ...

3
9

Since Postgres 9.3 there is a solution for invoking external programs. It is - for security reasons - limited to superusers and IMHO intended for exporting data, rather than doing a "notification on trigger":

COPY (SELECT 1) TO PROGRAM '/bin/touch /tmp/created_by_postgres'

If you want to actually export data to the invoked programm, you can provide any SELECT or a table name instead of SELECT 1. The query results will then be passed to the invoked program via its standard input.

You can find documentation of the feature in the Postgres docs: http://www.postgresql.org/docs/9.3/static/sql-copy.html

3
  • Hello, could you please explain why you have two paths in your arguments /bin/touch and /tmp/created_by_postgres? Do you think this would work to execute an external python or shell script? Aug 7, 2018 at 5:43
  • Alright, I understand that PROGRAM can actually run any shell command... Would you happen to know if there is a handshake between the postgres function executing the COPY method and the shell command executed by PROGRAM? Meaning the postgres function would wait for the shell command to complete before moving to its next task. Aug 7, 2018 at 6:17
  • With great power comes great responsibility. The manual: "COPY naming a file or command is only allowed to database superusers or users who are granted one of the roles pg_read_server_files, pg_write_server_files, or pg_execute_server_program, since it allows reading or writing any file or running a program that the server has privileges to access." Feb 14 at 22:25
0

You can execute external scripts from inside trigger function with an "untrusted" language, like plpythonu. More details here: https://www.postgresql.org/docs/current/plpython.html

Trigger function example:

CREATE FUNCTION execute_python_script()
RETURNS trigger
AS $$
begin

import subprocess
result = subprocess.run(['/path/to/your/bin/python', '/some_folder/some_sub_folder/script.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

end;
$$ 
LANGUAGE plpythonu;

Trigger example:

CREATE TRIGGER trigger_name
AFTER INSERT ON table
EXECUTE PROCEDURE execute_python_script();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.