Detecting Postgresql Table Change for LiveView

So I have a table of MediaItems and when that list changes, say new entries, I’d like LiveView to know about that so that the Timeline updates automatically. How to know when the table updates? I’ve seen supabase but that appears to be for JS.

2 Likes

You are looking for Change Data Capture which goes well beyond the scope of PostgreSQL. If you can achieve CDC with your DB then you should be able to pretty easily propagate events to any other frontend/backend system, LiveView included.

2 Likes

Hi thanks for the reply because I never heard of CDC before(probably because when it comes to backend development I’m just a novice). I do think though that CDC goes way beyond the scope of what I’m looking for. I’m just trying to learn LiveView and everything I’ve found about is so far in terms of examples is user-initiated actions changing state rather than server events. I think if I followed this CDC path I would get bogged-down in the details of CDC rather than develop the frontend.

2 Likes

You might use postgresql triggers to be notified when tables update.

I remember following this post when doing so…

2 Likes

Triggers definitely don’t scale well though. They slow down the database exponentially with every new one you add. Of course for many apps it won’t ever matter and they are indeed the easiest way out.


@michael it really depends on your goal. If you just want to capture a monotonically increasing log of user actions and act on them then what you said is absolutely going to work. But don’t forget that sometimes net hiccups happen, people get pissed and start clicking an element 20 times until the UI unfreezes etc. :smiley: That’s why I offer CDC, as complex as it is, because all of your code is going to “drink from the same well”.

But I get that you don’t want complexity so you could try with DB triggers.

2 Likes

You use Phoenix PubSub to broadcast them each time you create, update or delete them.

Then in the handle_info on your live view you can use send_update/2 to update the client.

Some useful links:

6 Likes