Skip to content

Instantly share code, notes, and snippets.

@cozingo
Last active August 17, 2024 09:59
Show Gist options
  • Save cozingo/308360c4bf8dd2d58fc3ef8898d99dfe to your computer and use it in GitHub Desktop.
Save cozingo/308360c4bf8dd2d58fc3ef8898d99dfe to your computer and use it in GitHub Desktop.
log every insert/update/delete of each table in db
DO $$
DECLARE
table_name TEXT;
trigger_name TEXT;
query TEXT;
BEGIN
FOR table_name IN
SELECT tablename
FROM pg_tables
WHERE schemaname = 'public'
AND tablename <> 'operation_logs'
LOOP
trigger_name := 'log_' || table_name || '_insert_update_delete';
query := 'CREATE TRIGGER ' || trigger_name ||
' AFTER INSERT OR UPDATE OR DELETE ON ' || table_name ||
' FOR EACH ROW EXECUTE FUNCTION log_sql_operations();';
EXECUTE query;
END LOOP;
END $$;
CREATE TRIGGER log_insert_update_delete_table_name
AFTER INSERT OR UPDATE OR DELETE ON table_name
FOR EACH ROW EXECUTE FUNCTION log_sql_operations();
CREATE OR REPLACE FUNCTION log_sql_operations() RETURNS TRIGGER AS $$
DECLARE
executed_sql TEXT;
BEGIN
IF TG_OP = 'INSERT' THEN
executed_sql := 'INSERT INTO ' || TG_TABLE_NAME || ' VALUES (' || quote_literal(NEW.*) || ');';
INSERT INTO operation_logs (operation_type, table_name, executed_sql)
VALUES (TG_OP, TG_TABLE_NAME, executed_sql);
RETURN NEW;
ELSIF TG_OP = 'UPDATE' THEN
executed_sql := 'UPDATE ' || TG_TABLE_NAME || ' SET ' || quote_literal(NEW.*) || ' WHERE ' || quote_literal(OLD.*) || ';';
INSERT INTO operation_logs (operation_type, table_name, executed_sql)
VALUES (TG_OP, TG_TABLE_NAME, executed_sql);
RETURN NEW;
ELSIF TG_OP = 'DELETE' THEN
executed_sql := 'DELETE FROM ' || TG_TABLE_NAME || ' WHERE ' || quote_literal(OLD.*) || ';';
INSERT INTO operation_logs (operation_type, table_name, executed_sql)
VALUES (TG_OP, TG_TABLE_NAME, executed_sql);
RETURN OLD;
END IF;
END;
$$ LANGUAGE plpgsql;
CREATE TABLE operation_logs (
id SERIAL PRIMARY KEY,
operation_type VARCHAR(10),
table_name VARCHAR(50),
operation_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
executed_sql TEXT
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment