Detecting column changes in a postgres update trigger

后端 未结 3 361
清歌不尽
清歌不尽 2021-01-12 05:34

I have a postgres database with several tables that I want to watch for updates on, and if there\'s any updates, I want to fire a \"hey, something changed\" update. This wor

相关标签:
3条回答
  • 2021-01-12 05:41

    http://www.postgresql.org/docs/9.3/static/plpython-trigger.html

    TD["table_name"]
    

    I do exactly the same type of notify, I loop through all of the columns like this:

        for k in TD["new"]:
            if TD["old"][k] != TD["new"][k]:
                changed.append(k)
    

    changed.append(k) builds my notification string. Somewhere else I do a listen, then broadcast the results out pub/sub to web socket clients.

    -g

    0 讨论(0)
  • 2021-01-12 05:47

    Another way is to exploit JSON/JSONB functions that come in recent versions of PostgreSQL. It has the advantage of working both with anything that can be converted to a JSON object (rows or any other structured data), and you don't even need to know the record type.

    See my original StackOverflow post with appropriate examples.

    0 讨论(0)
  • 2021-01-12 06:02

    Read up on the hstore extension. In particular you can create a hstore from a row, which means you can do something like:

    changes := hstore(NEW) - hstore(OLD);
    ...pg_notify(... changes::text ...)
    

    That's slightly more information than you wanted (includes new values). You can use akeys(changed) if you just want the keys.

    0 讨论(0)
提交回复
热议问题