在 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_dropped_objects() 函数,类似于pg_event_trigger_ddl_commands()。
很遗憾,Postgres 9.4 中没有 pg_event_trigger_ddl_commands()。您可以尝试使用current_query() 获取插入/更改的对象,或在C 中编写触发函数。我认为更简单的方法是将 Postgres 升级到 9.5+。