Last active
January 18, 2019 10:01
-
-
Save t0mdicks0n/20c831920506a3a3f976bc817d2254d7 to your computer and use it in GitHub Desktop.
Simple little way to store all INSERTS on a PSQL-database in a form of a audit log. Can be really useful for testing. For production some performance tweaks would have to be made.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Create a table for test | |
CREATE TABLE example_table ( | |
ts timestamp with time zone, | |
name TEXT, | |
age INT | |
); | |
-- Create a audit table where all queries will be stored | |
CREATE TABLE example_audit_table ( | |
created_at timestamp default current_timestamp, | |
query TEXT | |
); | |
-- Write a really simple trigger to access and write all | |
-- the queries to the audit table. | |
CREATE OR REPLACE FUNCTION log_query() | |
RETURNS TRIGGER AS | |
$$ | |
BEGIN | |
INSERT INTO example_audit_table(query) VALUES (NEW::text); | |
RETURN NULL; | |
END; | |
$$ LANGUAGE plpgsql; | |
-- Attatch the trigger to the table | |
CREATE TRIGGER example_table_audit_log | |
AFTER INSERT OR UPDATE ON example_table | |
FOR EACH ROW EXECUTE PROCEDURE log_query(); | |
-- Test it out by inserting some random data | |
INSERT INTO example_table ( | |
ts, | |
name, | |
age | |
) VALUES ( | |
'2018-09-26 08:00:32', | |
'Tom', | |
10 | |
); | |
-- Check out the data | |
SELECT * FROM example_audit_table; | |
/* | |
created_at | query | |
----------------------------+----------------------------------- | |
2018-10-03 08:59:58.770585 | ("2018-09-26 08:00:32+00",Tom,10) | |
(1 row) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment