如何使用golang捕获新的postgreSQL记录事件

5

我有一个脚本可以连接到数据库并从中获取数据,我能否通过某种方式让它在数据库表中添加新记录时通知我?


3
NOTIFY相关工具可能会引起兴趣。据我所知,您需要在要监视的表上设置插入触发器,但我不确定这些功能与Go的PostgreSQL接口的兼容性如何。 - mu is too short
看一下Postgresql的Listen/Notify功能。 https://www.postgresql.org/docs/9.3/static/sql-listen.html 你可以创建一个监听器,向通道发送NOTIFY消息。 你可以在golang中监听该通道。 - Feralus
2个回答

7

您可以使用 Postgresql 的 LISTEN/NOTIFY 特性。

使用 "github.com/lib/pq",您可以轻松地获取通知事件并对新的数据库事件做出反应。

以下是 Go 实现的示例


6

使用SQL触发器和go-pg库解决了这个问题:

  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'.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接