问题
我经常看到它说 rules should be avoided and triggers used instead .我可以看到规则系统中的危险,但肯定有规则的有效用途,对吗?它们是什么?
我问这个是出于普遍的兴趣;我对数据库不是很熟悉。
可能是有效用途的示例
例如,过去我需要锁定某些数据,所以我做了这样的事情:
CREATE OR REPLACE RULE protect_data AS
ON UPDATE TO exampletable -- another similar rule for DELETE
WHERE OLD.type = 'protected'
DO INSTEAD NOTHING;
然后如果我想编辑 protected 数据:
START TRANSACTION;
ALTER TABLE exampletable DISABLE RULE protect_data;
-- edit data as I like
ALTER TABLE exampletable ENABLE RULE protect_data;
COMMIT;
我同意这是 hacky,但在这种情况下我无法更改访问数据库的应用程序(甚至无法向其抛出错误)。因此,奖励积分可以找到为什么这是对规则系统的危险/无效使用的原因,但不是为什么这是糟糕的设计。
最佳答案
RULES 的一个用例是可更新的 View (尽管在 9.1 中发生了变化,因为该版本引入了 View 的 INSTEAD OF 触发器)
另一个很好的解释可以在手册中找到:
For the things that can be implemented by both, which is best depends on the usage of the database. A trigger is fired for any affected row once. A rule manipulates the query or generates an additional query. So if many rows are affected in one statement, a rule issuing one extra command is likely to be faster than a trigger that is called for every single row and must execute its operations many times. However, the trigger approach is conceptually far simpler than the rule approach, and is easier for novices to get right.
(取自:http://www.postgresql.org/docs/current/static/rules-triggers.html)
关于database - PostgreSQL 规则有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5894142/