How can I catch an event of a new postgreSQL record with golang

Viewed 5715

I have a script that connects to DB and can get data from it Can I somehow make it to notify me, when any new record is added to the DB table

2 Answers

You can use LISTEN/NOTIFY features of Postgresql.

With "github.com/lib/pq", you can easily fetch notify-events and react to new database-events.

Here is an example of the go implementation.

Solved this using sql triggers and go-pg library:

  1. Create sql function called insert_test_func, that on INSERT do:

    PERFORM pg_notify('mychan', 'Message');
    
  2. Create trigger, that executes func:

    create trigger check_insert 
    before insert or update on *my_table_name*
    for each row 
    execute procedure insert_test_func();
    
  3. Execute this trigger

  4. With github.com/go-pg/pg, connect to the DB and with pg.Listen() listening to the channel for the 'Message'.

Related