database - PostgreSQL 规则有什么用?

标签 database postgresql triggers rules

问题

我经常看到它说 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/

相关文章:

python - mySql 数据库在 0x104e18ea0 处有 sqlite3.Cursor 对象作为表中的输出

php - 添加了 if else 参数和从数据库中丢失的变量

mysql - MariaDB - 我应该为我的表添加索引吗?

postgresql - Airflow sql炼金术池大小被忽略

java - 如何在关系数据库中保留大字符串字段的编辑历史

sql 触发器未按预期工作

wpf - 当 ListView 的 SelectedItem 从 null 更改时启用按钮并执行相反的操作

mysql - 比较mysql触发器中的字符串

database - 是否可以将 sdf umbraco 数据库转换为 Azure SQL?

c# - 在 Entity Core 中使用 Postgres lpad