Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Auditing/versioning of Table Modifications on PostgreSQL

We're implementing a New system using Java/Spring/Hibernate on PostgreSQL. This system needs to make a copy of Every Record as soon as a modification/deletion is done on the record(s) in the Tables(s). Later, the Audit Table(s) will be queried by Reports to display the data to the users.

I was planning to implement this auditing/versioning feature by having a trigger on the table(s) which would make a copy of the modified row(deleted row) "TO" a TABLE called ENTITY_VERSIONS which would have about 20 columns called col1, col2, col3, col4, etc which would store the columns from the above Table(s); However, the problem is that if there is more than 1 Table to be versioned and ONLY 1 TARGET table(ENTITY_VERSIONS) to store all the tables' versions, how do I design the TARGET table ?

OR is it better that there will be a COPY of the VERSION Table for each Table that needs versioning ?

It will be bonus if some pointers towards PostgreSQL Triggers (and associated Stored Procedure ) code for implementing the auditing/versioning can be shared.

P.S : I looked at Suggestions for implementing audit tables in SQL Server? and kinda like the answer except I would NOT know what type should OldValue and NewValue be ?

P.P.S : If the Tables use SOFT DELETEs (phantom deletes) instead of HARD deletes, do any of your advice change ?

like image 625
anjanb Avatar asked Jul 06 '10 13:07

anjanb


People also ask

How do I enable auditing in PostgreSQL?

The basic way to enable an audit trail in PostgreSQL is to enable log_statement=all. However, this will simply list all database operations—it won't let you filter certain operations, and will not generate logs in the format needed for auditing. pgAudit provides these capabilities.

What is audit table in PostgreSQL?

Audit tables record changes that occur to rows in another table. They're like commit logs for database tables, and they're typically used to figure out who made what changes when.


2 Answers

I would have a copy of each table to hold the versions of that table you wish to keep. It sounds like a bit of a nightmare to maintain and use a global versioning table.

This link in the Postgres documentation shows some audit trigger examples in Postgres.

like image 57
rfusca Avatar answered Sep 28 '22 06:09

rfusca


In global table all columns can be stored in single column as hstore type. I just tried audit and I it is works great, I recommend it. Awesome audit table example tracks all changes in single table by simply adding a trigger onto the tables you want to begin to keep audit history on. all changes are stored in as hstore type- works for v 9.1+ this link

like image 33
roger Avatar answered Sep 28 '22 06:09

roger