赞
踩
和oracle类似,pg中触发器除了支持普通的dml触发器,还支持ddl语句,便是通过事件触发器实现的。
事件触发器,当数据库中发生某些DDL或DCL事件(ddl_command_start,ddl_command_end,sql_drop,table_rewrite)时,可以被捕获,并触发调用用户定义的事件触发器函数。
语法:
CREATE EVENT TRIGGER name
ON event
[ WHEN filter_variable IN (filter_value [, ... ]) [ AND ... ] ]
EXECUTE { FUNCTION | PROCEDURE } function_name()
目前的事件触发器支持的command tag见:
https://www.postgresql.org/docs/12/event-trigger-matrix.html
使用事件触发器,和普通触发器的使用类似,都需要先创建触发器函数,然后创建事件触发器,不同的是事件触发器函数返回的是event_trigger。
例子:
例如创建一个触发器函数来实现禁止用户创建和删除表。
创建触发器函数:
bill=# create or replace function f_abort() returns event_trigger as $$
declare
begin
if current_user='test1' then
RAISE EXCEPTION 'event:%, command:%', tg_event, tg_tag;
end if;
end;
$$ language plpgsql strict;
CREATE FUNCTION
创建事件触发器;
bill=# create event trigger a on ddl_command_start when TAG IN ('CREATE TABLE', 'DROP TABLE') execute procedure f_abort();
CREATE EVENT TRIGGER
测试test1用户是否可以创建删除表(无法创建删除了):
bill=# \c bill test1
You are now connected to database "bill" as user "test1".
bill=> create table tt1(id int);
ERROR: event:ddl_command_start, command:CREATE TABLE
CONTEXT: PL/pgSQL function f_abort() line 5 at RAISE
bill=> drop table t;
ERROR: event:ddl_command_start, command:DROP TABLE
CONTEXT: PL/pgSQL function f_abort() line 5 at RAISE
测试其它用户是否可以创建删除表(未受到影响):
bill=> \c bill bill
You are now connected to database "bill" as user "bill".
bill=# create table tt1(id int);
CREATE TABLE
bill=# drop table tt1;
DROP TABLE
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。