Database Research & Development

  • Home
  • NoSQL
    • NoSQL
    • Cassandra
  • Databases
    • Database Theory
    • Database Designing
    • SQL Server Coding Standards
    • SQL Server
    • PostgreSQL
    • MySQL
    • Greenplum
    • Linux
  • Interviews
    • SQL Server Interviews
    • MySQL Interviews
    • SQL Puzzles
  • DBA Scripts
    • SQL Server DBA Scripts
    • PostgreSQL DBA Scripts
    • MySQL DBA Scripts
    • Greenplum DBA Scripts
  • Home
  • Blog Archives !
  • (: Laugh@dbrnd :)
  • Contact Me !
sqlserverinterviews
Home 2017 April PostgreSQL: Create Audit Trigger, for logging or Auditing your Database DML Transactions

PostgreSQL: Create Audit Trigger, for logging or Auditing your Database DML Transactions

This article is half-done without your Comment! *** Please share your thoughts via Comment ***

If you experienced with SQL Server, You might know about SQL Server Audit and Change Data Capture (CDC) functionality.
As per the PostgreSQL WIKI, PostgreSQL does not have such an Inbuilt functionality for auditing your user transactions.

Most of the Application requires, Database auditing like Who Inserted, When Updated kind of DML Transactions.
Here, I am sharing one demonstration about Trigger Approach, which is not always good, but for specific requirement, we can go with this approach.

I have created separate schema and table to log about DML transactions.
PostgreSQL Database Administrator can use this trigger for security purpose also.

Create a one new Schema:

1
CREATE SCHEMA AuditTable;

Create a new table for Logged Transaction:

1
2
3
4
5
6
7
8
9
10
11
CREATE TABLE AuditTable.tbl_LoggedTransactions
(
SchemaName CHARACTER VARYING
,TableName CHARACTER VARYING
,UserName CHARACTER VARYING
,DMLAction CHARACTER VARYING
,OriginalData TEXT
,ExecutedNewData TEXT
,ExecutedSQL TEXT
,RecordDateTime TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW()
);

Revoke all access of newly creatd table from PUBLIC:

1
REVOKE ALL ON AuditTable.tbl_LoggedTransactions FROM public;

Create one trigger function for auditing DML transactions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
CREATE OR REPLACE FUNCTION AuditTable.trg_AuditDML()
RETURNS TRIGGER
AS $BODY$
DECLARE
OldData TEXT;
NewData TEXT;
BEGIN
IF (TG_OP = 'UPDATE') THEN
OldData := ROW(OLD.*);
NewData := ROW(NEW.*);
INSERT INTO AuditTable.tbl_LoggedTransactions
(
SchemaName
,TableName
,UserName
,DMLAction
,OriginalData
,ExecutedNewData
,ExecutedSQL
)
VALUES
(
TG_TABLE_SCHEMA::TEXT
,TG_TABLE_NAME::TEXT
,session_user::TEXT
,substring(TG_OP,1,1)
,OldData
,NewData
,current_query()
);
RETURN NEW;
ELSIF (TG_OP = 'DELETE') THEN
OldData := ROW(OLD.*);
INSERT INTO AuditTable.tbl_LoggedTransactions
(
SchemaName
,TableName
,UserName
,DMLAction
,OriginalData
,ExecutedSQL
)
VALUES
(
TG_TABLE_SCHEMA::TEXT
,TG_TABLE_NAME::TEXT
,session_user::TEXT
,substring(TG_OP,1,1)
,OldData
,current_query()
);
RETURN OLD;
ELSIF (TG_OP = 'INSERT') THEN
NewData := ROW(NEW.*);
INSERT INTO AuditTable.tbl_LoggedTransactions
(
SchemaName
,TableName
,UserName
,DMLAction
,ExecutedNewData
,ExecutedSQL
)
VALUES
(
TG_TABLE_SCHEMA::TEXT
,TG_TABLE_NAME::TEXT
,session_user::TEXT
,substring(TG_OP,1,1)
,NewData
,current_query()
);
RETURN NEW;
ELSE
RAISE WARNING '[AuditTable.trg_AuditDML] - Other action occurred: %, at %',TG_OP,now();
RETURN NULL;
END IF;
END;
$BODY$
LANGUAGE plpgsql;

Create a sample table:

1
2
3
4
5
CREATE TABLE public.tbl_Employees
(
EmpID INT
,EmpName CHARACTER VARYING
);

Create trigger on tbl_Employees with the use of trigger function AuditTable.trg_AuditDML:

1
2
3
CREATE TRIGGER trg_tbl_Employees_INSERT_UPDATE_DELETE
AFTER INSERT OR UPDATE OR DELETE ON public.tbl_Employees
FOR EACH ROW EXECUTE PROCEDURE AuditTable.trg_AuditDML();

Execute few sample DMLs:

1
2
3
4
5
6
7
8
INSERT INTO tbl_Employees VALUES
(1,'Anvesh'),(2,'Martin'),(3,'Roy')
,(4,'Jeeny'),(5,'Kavita'),(6,'Neevan');
 
UPDATE tbl_Employees SET EmpName='Mahi'
WHERE EmpID = 5;
 
DELETE FROM tbl_Employees WHERE EmpID = 4;

Check AuditTable.tbl_LoggedTransactions table for logged DML transaction:

1
SELECT *FROM AuditTable.tbl_LoggedTransactions;

Apr 5, 2017Anvesh Patel
NoSQL: Create user defined type in CassandraPostgreSQL: Use pg_backend_pid to get your current Process ID (Session ID)
Comments: 4
  1. IDM
    March 4, 2018 at 11:55 am

    I know this if off topic but I’m looking into starting my
    own weblog and was curious what all is required to get setup?
    I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very internet smart so I’m not 100% positive.

    Any suggestions or advice would be greatly appreciated.
    Thanks

    ReplyCancel
  2. swagat sahoo
    September 26, 2018 at 3:28 pm

    Hi Anvesh,
    I am daily follower of your blogs,
    i have a qsn ::::
    How can i insert the error information into a log table and at the same time ,
    if any invalid data trying to insert or delete or fetching into or from table ,at that time one exception will raise ,that will print you are trying to process invalid data.

    ReplyCancel
    • Anvesh Patel
      Anvesh Patel
      October 3, 2018 at 7:16 pm

      You cant insert error message here, because it logs successful transactions only. For error logs, visit logs folder and there you can do some python script automation.

      ReplyCancel
  3. HARIATY
    May 13, 2019 at 2:22 am

    hi, i try that all, and it’s working. thank you so muchhhhhhhh.
    God bless you šŸ™‚

    ReplyCancel

Leave a Reply to Anvesh Patel Cancel reply

CAPTCHA
Refresh

*

Anvesh Patel
Anvesh Patel

Database Engineer

April 5, 2017 4 Comments PostgreSQLAnvesh Patel, Audit DELETE, Audit INSERT, Audit Transaction, Audit Trigger, Audit UPDATE, Data Security, database, database research and development, dbrnd, Logging DML, plpgsql, Postgres Query, postgresql, PostgreSQL Administrator, PostgreSQL Error, PostgreSQL Programming, PostgreSQL Tips and Tricks
About Me!

I'm Anvesh Patel, a Database Engineer certified by Oracle and IBM. I'm working as a Database Architect, Database Optimizer, Database Administrator, Database Developer. Providing the best articles and solutions for different problems in the best manner through my blogs is my passion. I have more than six years of experience with various RDBMS products like MSSQL Server, PostgreSQL, MySQL, Greenplum and currently learning and doing research on BIGData and NoSQL technology. -- Hyderabad, India.

About DBRND !

dbrnd

This is a personal blog (www.dbrnd.com).

Any views or opinions represented in this blog are personal and belong solely to the blog owner and do not represent those of people, institutions or organizations that the owner may or may not be associated with in professional or personal capacity, unless explicitly stated.

Feel free to challenge me, disagree with me, or tell me I’m completely nuts in the comments section of each blog entry, but I reserve the right to delete any comment for any reason whatsoever (abusive, profane, rude, or anonymous comments) - so keep it polite.

The content of this website is protected by copyright. No portion of this website may be copied or replicated in any form without the written consent of the website owner.

Recent Comments !
  • Anvesh Patel { Sure will do... } – May 27, 12:43 PM
  • Anvesh Patel { Great... } – May 27, 12:41 PM
  • Anvesh Patel { Great... } – May 27, 12:39 PM
  • Anvesh Patel { Great... } – May 27, 12:36 PM
  • Anvesh Patel { Great... } – May 27, 12:28 PM
  • Anvesh Patel { Great... } – May 27, 12:27 PM
  • Anvesh Patel { Great... } – May 27, 12:16 PM
  • Older »
Follow Me !
  • facebook
  • linkedin
  • twitter
  • youtube
  • google
  • flickr
Ā© 2015 – 2019 All rights reserved. Database Research & Development (dbrnd.com)
Posting....