在Postgres Trigger功能中进行例外调用之前执行操作
Postgres 8.4这里。想象
CREATE FUNCTION emp_stamp() RETURNS trigger AS $emp_stamp$
BEGIN
-- Check that empname and salary are given
IF NEW.empname IS NULL THEN
RAISE EXCEPTION 'empname cannot be null';
END IF;
IF NEW.salary IS NULL THEN
RAISE EXCEPTION '% cannot have null salary', NEW.empname;
END IF;
-- Who works for us when she must pay for it?
IF NEW.salary < 0 THEN
RAISE EXCEPTION '% cannot have a negative salary', NEW.empname;
END IF;
-- Remember who changed the payroll when
NEW.last_date := current_timestamp;
NEW.last_user := current_user;
RETURN NEW;
END;
$emp_stamp$ LANGUAGE plpgsql;
如果我们想执行诸如在自定义表中登录的事情,以下例外:
-- Check that empname and salary are given
IF NEW.empname IS NULL THEN
INSERT INTO my_log_table ('User didn't supplied empname')
RAISE EXCEPTION 'empname cannot be null';
END IF;
它不会起作用,因为我们在提高异常之前放置的任何内容
call the Rollback 提高异常
意味着,即我们创建的My_log_table行只有 rish five exception
即可删除。
完成这样的事情的最佳方法是什么?也许会发现我们的自定义例外?
我需要关闭回滚 @触发器。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以 /捕获异常。
在
异常
块中,您可以做任何其他事情,例如insert
在另一个表中。之后,您可以重新调整异常以传播,但这会卷回整个事务,包括insert
到日志表(除非将异常包装并捕获在外部功能中)。您可以:
使用dblink呼叫之类的技巧模仿自主事务,当包装交易退回时,该交易并未撤消。相关:
提高
a a通知
警告< /code>另外,
ROOLBACK
。提高
与您自己的文本不同的异常另外,您只需取消触发触发功能的行,而不是 提出异常。交易中的其他所有内容正常进行。
假设这是更新上的触发
,并且您有另一个具有相同结构的表,以写入失败
insert
s to:请注意,
new
包含异常发生之前的行,包括同一功能中的先前成功语句。扳机:
You can trap errors / catch exceptions.
In the
EXCEPTION
block you can do anything else, likeINSERT
into another table. Afterwards you could re-raise the exception to propagate out, but that would roll back the whole transaction including theINSERT
to the log table (unless the exception is wrapped and caught in an outer function).You could:
use tricks like a dblink call to emulate an autonomous transaction, which isn't undone, when the wrapping transaction is rolled back. Related:
RAISE
aNOTICE
orWARNING
additionally, which also isn't undone byROOLBACK
.RAISE
a differentEXCEPTION
with your own text.Alternatively, you can just cancel the row that triggered the trigger function and not raise an exception. Everything else in the transaction goes through normally.
Assuming this is a trigger
ON UPDATE
and you have another table with identical structure to write failedINSERT
s to:Note that
NEW
contains the state of the row right before the exception occurred, including previous successful statements in the same function.Trigger:
实际上,您有两个选择。
You have two options actually.