作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在交易中创建记录。
begin;
update parent_records where id=5 set closed = now();
insert into child_records ...;
commit;
一旦父记录关闭
,我想阻止插入新的 child_records。似乎在 parent_records 上设置规则以在关闭时在 update
操作上爆炸将解决问题,因为交易会失败。
我可以使用 where closed is null
进行更新,然后检查应用程序代码是否有任何行被更新和回滚,但我宁愿约束在数据库本身中。
当满足条件(closed
列不为空)时,如何将父行标记为不可变(更新失败并出现错误)?
最佳答案
使用触发器,例如:
create function before_update_on_parent_records()
returns trigger language plpgsql as $$
begin
if old.closed is not null then
raise exception 'cannot update because the row is closed';
end if;
return new;
end $$;
create trigger before_update_on_parent_records
before update on parent_records
for each row execute procedure before_update_on_parent_records();
关于postgresql - 有没有办法在给定条件的情况下声明 postgresql 行不可变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35162297/
我是一名优秀的程序员,十分优秀!