我想验证向某些表添加触发器的数据库迁移的正确性。我正在使用 sqitch ,所以我想找到一种方法来使用 SQL 查询来检查它。我相信 postgres 系统表应该是可能的,但我目前找不到执行此操作的方法。
最佳答案
使用目录pg_trigger .
表 books
的简单查找:
select tgname
from pg_trigger
where not tgisinternal
and tgrelid = 'books'::regclass;
tgname
---------------
books_trigger
(1 row)
使用 pg_proc
获取触发函数的来源:
select tgname, proname, prosrc
from pg_trigger
join pg_proc p on p.oid = tgfoid
where not tgisinternal
and tgrelid = 'books'::regclass;
tgname | proname | prosrc
---------------+---------------+------------------------------------------------
books_trigger | books_trigger | +
| | begin +
| | if tg_op = 'UPDATE' then +
| | if new.listorder > old.listorder then +
| | update books +
| | set listorder = listorder- 1 +
| | where listorder <= new.listorder +
| | and listorder > old.listorder +
| | and id <> new.id; +
| | else +
| | update books +
| | set listorder = listorder+ 1 +
| | where listorder >= new.listorder +
| | and listorder < old.listorder +
| | and id <> new.id; +
| | end if; +
| | else +
| | update books +
| | set listorder = listorder+ 1 +
| | where listorder >= new.listorder +
| | and id <> new.id; +
| | end if; +
| | return new; +
| | end
(1 row)
pg_get_triggerdef()
的示例函数使用:
select pg_get_triggerdef(t.oid) as "trigger declaration"
from pg_trigger t
where not tgisinternal
and tgrelid = 'books'::regclass;
trigger declaration
--------------------------------------------------------------------------------------------------------------
CREATE TRIGGER books_trigger BEFORE INSERT OR UPDATE ON books FOR EACH ROW EXECUTE PROCEDURE books_trigger()
(1 row)
在 Sqitch verify
脚本中,您可以使用匿名代码块,例如:
do $$
begin
perform tgname
from pg_trigger
where not tgisinternal
and tgrelid = 'books'::regclass;
if not found then
raise exception 'trigger not found';
end if;
end $$;
关于sql - 如何检查 PostgreSQL 中是否存在触发器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33174638/