Search code examples
sqlrubypostgresqlsql-insertsql-delete

Ruby File that Will Log All SQL INSERTs and SQL DELETEs (and only those commands)


I am working with a PostgreSQL database. I have written a .rb file I am using to manipulate data in the database. I want to be able to log all the SQL INSERTs and DELETEs elicited by this file. How do I go about that?


Solution

  • At the start of your script, create the needed temporary tables, and adds two triggers, one on insert, one on delete, and have them fire for each row accordingly. it also works with rules:

    create temporary table foo_log_ins (like foo);
    
    create rule log_foo_ins as
    on insert to foo
    do also
    insert into foo_log select new.*;
    
    create temporary table foo_log_del (like foo);
    
    create rule log_foo_del as
    on delete to foo
    do also
    insert into foo_log_del select old.*;