PostgreSQL 触发插入带有参数的外部脚本
PostgreSQL trigger on insert external script with arguments
我创建了调用带有参数的外部脚本的函数:
CREATE OR REPLACE FUNCTION foo3(text, text) RETURNS TEXT AS $$
$ip = shift;
$username = shift;
$cmd="/bin/echo -n $ip $username > /tmp/test";
return `$cmd`;
$$ LANGUAGE plperlu;
手动执行时效果很好。
但是我想每次在我的 table 中插入新记录时调用它(作为记录值的传递参数):
postgres=# CREATE TRIGGER t_foo
postgres-# BEFORE UPDATE
postgres-# ON mapping
postgres-# FOR EACH ROW
postgres-# EXECUTE PROCEDURE foo3(OLD.ip, OLD.username);
ERROR: syntax error at or near "."
LINE 5: EXECUTE PROCEDURE foo3(OLD.ip, OLD.username);
^
很明显,我无法将任何参数传递给该函数。如何解决?
The trigger function must be declared as a function taking no arguments and returning type trigger.
您的函数既没有声明为 returns trigger
,也没有 "no arguments"。
您需要创建一个触发函数来调用您的函数:
create function foo_trigger_func()
<b>returns trigger</b>
as
$$
begin
perform foo3(old.ip, old.username);
end;
$$
language plpgsql;
然后使用该函数创建触发器:
CREATE TRIGGER t_foo
BEFORE UPDATE ON mapping
FOR EACH ROW
EXECUTE PROCEDURE foo_trigger_func();
我创建了调用带有参数的外部脚本的函数:
CREATE OR REPLACE FUNCTION foo3(text, text) RETURNS TEXT AS $$
$ip = shift;
$username = shift;
$cmd="/bin/echo -n $ip $username > /tmp/test";
return `$cmd`;
$$ LANGUAGE plperlu;
手动执行时效果很好。 但是我想每次在我的 table 中插入新记录时调用它(作为记录值的传递参数):
postgres=# CREATE TRIGGER t_foo
postgres-# BEFORE UPDATE
postgres-# ON mapping
postgres-# FOR EACH ROW
postgres-# EXECUTE PROCEDURE foo3(OLD.ip, OLD.username);
ERROR: syntax error at or near "."
LINE 5: EXECUTE PROCEDURE foo3(OLD.ip, OLD.username);
^
很明显,我无法将任何参数传递给该函数。如何解决?
The trigger function must be declared as a function taking no arguments and returning type trigger.
您的函数既没有声明为 returns trigger
,也没有 "no arguments"。
您需要创建一个触发函数来调用您的函数:
create function foo_trigger_func()
<b>returns trigger</b>
as
$$
begin
perform foo3(old.ip, old.username);
end;
$$
language plpgsql;
然后使用该函数创建触发器:
CREATE TRIGGER t_foo
BEFORE UPDATE ON mapping
FOR EACH ROW
EXECUTE PROCEDURE foo_trigger_func();