当前位置:   article > 正文

PostgreSQL事件触发器_pg 触发器 dblink perform

pg 触发器 dblink perform

和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()
  • 1
  • 2
  • 3
  • 4

目前的事件触发器支持的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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

创建事件触发器;

bill=# create event trigger a on ddl_command_start when TAG IN ('CREATE TABLE', 'DROP TABLE') execute procedure f_abort();    
CREATE EVENT TRIGGER
  • 1
  • 2

测试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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

测试其它用户是否可以创建删除表(未受到影响):

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/773726
推荐阅读
相关标签
  

闽ICP备14008679号