加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何跟踪PostgreSQL中任何函数的更改

发布时间:2020-12-13 15:58:57 所属栏目:百科 来源:网络整理
导读:我希望在PostgreSQL中的任何函数中跟踪更改. 示例 – 假设,我在postgesql数据库中有函数fun_name(),我正在进行函数修改. 现在,我想跟踪像这样的记录 DateTime,Schema_name,Function_name,old_func_text,new_func_text 请建议在postgresql中实现此目的的最佳
我希望在PostgreSQL中的任何函数中跟踪更改.

示例 – 假设,我在postgesql数据库中有函数fun_name(),我正在进行函数修改.

现在,我想跟踪像这样的记录

DateTime,Schema_name,Function_name,old_func_text,new_func_text

请建议在postgresql中实现此目的的最佳方法.

我正在研究https://www.postgresql.org/docs/9.3/static/sql-createeventtrigger.html的事件触发器

谢谢.

解决方法

在Postgres 9.5中有一个函数 pg_event_trigger_ddl_commands(),它可以在事件触发器中用于获取插入/更改对象的oid.

日志表:

create table function_log (
    datetime timestamp,schema_name text,function_name text,tag text,function_body text);

事件功能和触发器:

create or replace function public.on_function_event()
    returns event_trigger
    language plpgsql
as $function$
begin
    insert into function_log
    select now(),nspname,proname,command_tag,prosrc
    from pg_event_trigger_ddl_commands() e
    join pg_proc p on p.oid = e.objid
    join pg_namespace n on n.oid = pronamespace;
end
$function$;

create event trigger on_function_event
on ddl_command_end 
when tag in ('CREATE FUNCTION','ALTER FUNCTION')
execute procedure on_function_event();

例:

create or replace function test()
returns int as $$select 1; $$language sql;

create or replace function test()
returns int as $$select 2; $$language sql;

alter function test() immutable;

select *
from function_log;

          datetime          | schema_name | function_name |       tag       | function_body 
----------------------------+-------------+---------------+-----------------+---------------
 2017-02-26 13:05:15.353879 | public      | test          | CREATE FUNCTION |  select 1; 
 2017-02-26 13:05:15.353879 | public      | test          | CREATE FUNCTION |  select 2; 
 2017-02-26 13:05:15.353879 | public      | test          | ALTER FUNCTION  |  select 2; 
(3 rows)

您可以将DROP FUNCTION命令标记添加到触发器,然后以与pg_event_trigger_ddl_commands()类似的方式使用函数pg_event_trigger_dropped_objects().

不幸的是,Postgres 9.4中没有pg_event_trigger_ddl_commands().您可以尝试使用current_query()获取插入/更改的对象,或者在C中编写触发器函数.我认为更简单的方法是将Postgres升级到9.5.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读