Dynamic auditing of data with PostgreSQL trigger

℡╲_俬逩灬. 提交于 2019-12-02 13:41:26

问题


I'm interested in using the following audit mechanism in an existing PostgreSQL database.

http://wiki.postgresql.org/wiki/Audit_trigger

but, would like (if possible) to make one modification. I would also like to log the primary_key's value where it could be queried later. So, I would like to add a field named something like "record_id" to the "logged_actions" table. The problem is that every table in the existing database has a different primary key fieldname. The good news is that the database has a very consistent naming convention. It's always, _id. So, if a table was named "employee", the primary key is "employee_id".

Is there anyway to do this? basically, I need something like OLD.FieldByName(x) or OLD[x] to get value out of the id field to put into the record_id field in the new audit record.

I do understand that I could just create a separate, custom trigger for each table that I want to keep track of, but it would be nice to have it be generic.

edit: I also understand that the key value does get logged in either the old/new data fields. But, what I would like would be to make querying for the history easier and more efficient. In other words,

select * from audit.logged_actions where table_name = 'xxxx' and record_id = 12345;

another edit: I'm using PostgreSQL 9.1

Thanks!


回答1:


You didn't mention your version of PostgreSQL, which is very important when writing answers to questions like this.

If you're running PostgreSQL 9.0 or newer (or able to upgrade) you can use this approach as documented by Pavel:

http://okbob.blogspot.com/2009/10/dynamic-access-to-record-fields-in.html

In general, what you want is to reference a dynamically named field in a record-typed PL/PgSQL variable like 'NEW' or 'OLD'. This has historically been annoyingly hard, and is still awkward but is at least possible in 9.0.

Your other alternative - which may be simpler - is to write your audit triggers in plperlu, where dynamic field references are trivial.



来源:https://stackoverflow.com/questions/8301136/dynamic-auditing-of-data-with-postgresql-trigger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!